Data Visualization with ggplot2 Interview Questions for R Programming
25 Data Visualization with ggplot2 questions with answers for r programming roles — 8 easy, 11 medium, 6 hard.
About Data Visualization with ggplot2
ggplot2 is the standard for charts in R. This topic covers the grammar of graphics, aesthetics, geoms, facets, scales, themes, annotations, saving plots and interactive charts with plotly. You will also learn to pick the right chart, avoid misleading visuals, design for colour-blind readers and handle very large datasets.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
The grammar of graphics describes a plot as layers built from components: data, aesthetic mappings that link variables to visual properties like x, y and colour, geoms that draw shapes, stats that transform data, scales, coordinate systems, facets and themes. In ggplot2 you start with ggplot(data, aes(x, y)) and add layers with +, such as geom_point(). This makes complex charts systematic and easy to modify.
02
Which chart types would you use for comparing categories, trends and distributions?
For comparing categories I use a bar chart, sorted by value, or a dot plot when there are many categories. For trends over time I use a line chart with time on the x-axis. For distributions I use histograms or density plots for one variable and boxplots or violin plots to compare groups. For relationships between two numeric variables I use a scatter plot. I avoid pie charts beyond three or four slices.
03
Write ggplot2 code for a monthly sales line chart with points.
ggsave() saves the last plot or a named plot with exact size and resolution.
p <- ggplot(df, aes(city, sales)) + geom_col()
ggsave('output/sales_by_city.png', plot = p,
width = 8, height = 5, dpi = 300)
ggsave('output/sales_by_city.pdf', plot = p,
width = 8, height = 5) # vector, sharp at any zoom
# svg for web use
ggsave('output/sales_by_city.svg', plot = p)
06
Bars in your chart appear in alphabetical order instead of by value. How do you fix it?
ggplot2 orders discrete axes by factor levels, which default to alphabetical. I reorder the factor by the value with forcats: aes(x = fct_reorder(city, sales), y = sales), and add coord_flip() or put the category on the y-axis for long labels. For a fixed custom order, such as months or ratings, I set levels explicitly with factor(x, levels = c(...)). fct_infreq() orders by frequency for count bars.
07
What is the difference between base R graphics and ggplot2?
Base graphics use functions like plot(), hist() and barplot() that draw directly on a device, and you add elements with lines() or legend() step by step. They are quick for exploration. ggplot2 builds plots as objects from layers using the grammar of graphics, handles legends and facets automatically and is easier to style consistently. Base plots are fine for quick checks, while ggplot2 is preferred for reports and publications.
08
Your manager says your charts are confusing. How do you respond?
I would thank them and ask which part was unclear, such as too many colours, missing labels or an unclear message. In my internship this happened with a crowded chart of twelve product lines. I simplified it by highlighting the top three, greying the rest, adding a clear title stating the finding and labelling values directly. My manager found the new version easy to present, and I now review every chart for one clear message.
09
What is the difference between mapping and setting an aesthetic in ggplot2?
Mapping links an aesthetic to a variable inside aes(), so values change with the data and a legend is created, for example aes(colour = region). Setting fixes an aesthetic to a constant outside aes(), for example geom_point(colour = 'steelblue'). A common mistake is writing aes(colour = 'blue'), which treats 'blue' as a data value, creates a legend called blue and uses the default red colour instead.
10
What is the difference between geom_bar() and geom_col()?
geom_bar() counts rows for each x value by default using stat = 'count', so you give only x, for example the number of orders per city from raw data. geom_col() uses y values as they are, so you supply already summarised data, for example total sales per city. geom_bar(stat = 'identity') is equivalent to geom_col(). Using geom_bar() with a y aesthetic gives an error, which is a common beginner issue.
Facets split a plot into small multiples, one panel per category, sharing the same axes and geoms. facet_wrap(~ region) wraps panels for one variable, and facet_grid(rows = vars(segment), cols = vars(year)) creates a grid for two variables. scales = 'free_y' lets each panel have its own y-axis. Facets are often clearer than one chart with many overlapping coloured lines, for example comparing sales trends across ten states.
12
How do you customise scales, labels and themes in ggplot2?
This is overplotting. I reduce point size and add transparency with geom_point(alpha = 0.1, size = 0.5). Better options are geom_hex() or geom_bin2d(), which show density as colour, or geom_density_2d() contours. I could also plot a random sample for shape and a smoothed trend with geom_smooth() on the full data. If x values are discrete, geom_jitter() spreads points. The goal is to make density visible, not every point.
14
Some stakeholders are colour-blind. How do you design charts for them?
I use colour-blind-safe palettes such as viridis with scale_colour_viridis_d() or the Okabe-Ito palette, and avoid red-green contrasts. I never rely on colour alone: I add direct labels, different shapes or line types, and facets. I limit categories to around six colours and highlight one key series while greying the rest. I also check charts with a colour-blindness simulator, such as the colorblindr package, before sharing.
plotly's ggplotly() converts an existing ggplot into an interactive chart with hover tooltips, zoom and legend toggling. ggiraph adds interactive tooltips and selection to ggplot geoms with fine control. highcharter and echarts4r wrap JavaScript charting libraries, and leaflet builds interactive maps. These outputs work in R Markdown or Quarto HTML reports and Shiny apps. For static PDF reports, standard ggplot2 is still the better choice.
16
How do you add labels and annotations to a ggplot chart?
geom_smooth() adds a fitted trend line with a confidence band, using loess for small data and a GAM for large data by default, or method = 'lm' for a straight line. stat_summary() computes summaries of y for each x, for example stat_summary(fun = mean, geom = 'point') to plot group means, or fun.data = mean_cl_normal for error bars. Both let you show patterns without precomputing summaries.
Common problems are a truncated y-axis on bar charts, which exaggerates differences because bar length should start at zero, inconsistent scales across panels, 3D effects, cherry-picked time ranges, dual axes with arbitrary ranges and too many colours. Area or bubble charts can mislead when size is mapped to radius instead of area. Good practice is to start bars at zero, label units, cite the data source and show context such as targets or prior periods.
19
Tell me about a chart or visualization that changed a business decision.
Situation: the operations team believed late deliveries were spread evenly across the week. Task: I was asked to review delivery data. Action: in R I built a heatmap of late deliveries by weekday and hour with ggplot2, which showed a sharp cluster on Monday mornings linked to weekend order backlog. Result: management added a Sunday evening shift, and late deliveries dropped by about 18 percent the next quarter.
20
Leadership wants a single report page with 15 charts. How do you approach it?
I first ask which decisions the page supports and which three to five metrics matter most, because 15 charts usually hide the message. I put headline KPIs at the top, followed by trend charts and then breakdowns, with consistent colours, scales and a shared theme function. Less important views go to a drill-down tab in a Shiny or Quarto dashboard. I test the draft with one stakeholder and remove charts nobody uses.
21
Why are dual-axis charts discouraged and how does ggplot2 handle secondary axes?
Dual-axis charts plot two measures with different scales on one chart, and the visual relationship between the lines depends on arbitrary axis ranges, so readers can be misled about correlation. ggplot2 only allows a secondary axis that is a one-to-one transformation of the primary axis through sec_axis(), such as Celsius and Fahrenheit. For two different metrics, I prefer two aligned panels using facets or the patchwork package.
22
Rendering a ggplot with 10 million points is extremely slow. What would you do?
I first question whether all points are needed. I aggregate before plotting, for example binning into hexagons with geom_hex() or summarising by time interval. If raw points are required, the scattermore package rasterizes millions of points quickly, and ggrastr rasterizes just the point layer while keeping text as vector. Saving as PNG instead of PDF also helps, because vector files with millions of shapes are huge and slow to open.
23
What is the difference between coord_cartesian() limits and scale limits in ggplot2?
Setting limits with scale_y_continuous(limits = c(0, 100)) or ylim() removes data outside the range before statistics are calculated, which changes boxplots, smooth lines and bar totals and gives warnings about removed rows. coord_cartesian(ylim = c(0, 100)) only zooms the view, keeping all data in calculations. So for zooming into part of a chart without altering the summary, coord_cartesian() is the correct choice.
24
How would you create a reusable branded theme for all team charts?
The sf package stores spatial data as data frames with a geometry column, and ggplot2's geom_sf() draws them. You read shapefiles or GeoJSON with st_read(), join your data, for example sales by state, and fill polygons by value to make a choropleth. tmap is a dedicated thematic mapping package and leaflet builds interactive web maps. Coordinate reference systems must match, and st_transform() reprojects layers when they do not.
Frequently asked questions
How important is Data Visualization with ggplot2 in R Programming interviews?
ggplot2 is the standard for charts in R. This topic covers the grammar of graphics, aesthetics, geoms, facets, scales, themes, annotations, saving plots and interactive charts with plotly. You will also learn to pick the right chart, avoid misleading visuals, design for colour-blind readers and handle very large datasets.
How should I use the Data Visualization with ggplot2 sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.