Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 57 ยท Practice and Interview

Matplotlib Interview Questions

Prepare for data and Python interviews with 20 Matplotlib questions: pyplot vs OO, Figure vs Axes, savefig and dpi, shared axes, big data, backends. Runnable demos.

Interviewers for data analyst, data scientist and Python roles often ask a few Matplotlib questions, because plotting is where everyone's code ends up. The questions are rarely about obscure function arguments. They test whether you understand how the library is organized and whether you can pick the right chart and avoid common traps.

This page collects 20 typical questions, grouped by topic. Each has a short answer you could say out loud, and several have a small runnable demo that proves the point. Read the answer first, say it in your own words, then run the demo. If a topic feels shaky, follow the link to the full lesson.

What interviewers look for

Structure Figure, Axes, Axis, Artist.
Practice Subplots, saving, styling.
Scale Big data and memory.
Judgment The right chart for the question.

Short, accurate answers beat long ones.

1 / 2

Part 1: Structure and the two APIs

Q1. What is the difference between pyplot and the object-oriented API?

pyplot (plt.plot, plt.title) is a state machine: it keeps a "current figure" and a "current axes" and silently applies every call to them. The object-oriented API makes you hold the objects (fig, ax = plt.subplots()) and call methods on them (ax.plot, ax.set_title). pyplot is fine for quick exploration. For anything with more than one axes, in functions or in reusable code, prefer the OO style, because it is explicit about which axes receives each call. Both styles draw the same objects; pyplot is a thin layer over them. See pyplot vs the Object-Oriented API.

The classic pitfall is "the current axes is not the one I think". This demo creates two figures and shows where a bare plt.plot goes:

Python Q1: the 'current' figure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q2. What are Figure, Axes and Axis? What is the difference between Axes and Axis?

A Figure is the whole canvas: it owns one or more Axes, a title (suptitle), the size and the dpi. An Axes is one plot: the rectangle with the data, its two Axis objects, the title, labels, spines, legend and all drawn artists. An Axis is one number line (ax.xaxis, ax.yaxis): it owns the ticks, tick labels, locators and formatters. So "Axes" is the plot, "Axis" is the line with the ticks, and a normal Axes has exactly two Axis objects. Everything you see is an Artist. See Anatomy of a Figure.

Python Q2: walk the hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q3. Why does plt.subplots return a figure and axes, and what shape does the axes object have?

plt.subplots(nrows, ncols) creates the Figure and a grid of Axes in one call. With one plot you get a single Axes object. With a row or column you get a 1D NumPy array, and with a grid a 2D array, unless you pass squeeze=False, which always gives a 2D array. Flatten with axes.flat or axes.ravel() to loop over everything. See Multiple Subplots.

Q4. How do you update an existing plot instead of redrawing it?

Keep the artist that plot returns (line, = ax.plot(...)) and change its data with line.set_data or line.set_ydata, then redraw the canvas. This is what animations and interactive widgets do, and it is much faster than clearing and re-plotting. Note the comma: plot returns a list of lines.

Python Q4: update data in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 2: Layout, sharing and twin axes

Q5. How do you share axes between subplots, and why?

Pass sharex=True and/or sharey=True to plt.subplots, or sharex=ax1 when creating an Axes. Shared axes keep the same limits and ticks, so zooming one panel zooms the others, and the inner tick labels can be hidden. Use sharing whenever panels show the same quantity on the same scale, so the reader compares heights and positions honestly. Use "row" or "col" to share only within rows or columns. See Shared, Twin and Secondary Axes.

Python Q5: sharing limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q6. What is twinx, and what are the risks of a dual-axis chart?

ax.twinx() creates a second Axes on top of the first that shares the x axis but has its own y axis on the right. It lets you plot two quantities with different units, such as rainfall and temperature. The risks are visual: the relative scaling of the two axes is arbitrary, so you can make two series look correlated or diverging just by changing the limits. Color the axes to match the data, keep the story simple, and consider two stacked panels with a shared x axis instead. If the second scale is only a unit conversion, use secondary_yaxis with a function. See Shared, Twin and Secondary Axes.

Q7. constrained layout versus tight_layout: which do you use?

Both fix overlapping labels. tight_layout() is a one-time adjustment of the subplot margins. layout="constrained" (passed to plt.figure or plt.subplots) is a solver that keeps adjusting as you add colorbars, legends and suptitles, and it handles mosaics and colorbars better. In new code, prefer layout="constrained". See Figure Size, DPI and Layout.

Q8. How would you build a dashboard where one chart spans two columns?

Use plt.subplot_mosaic with a layout where a name repeats, such as [["trend", "trend"], ["bar", "hist"]]. Equal names merge into one wide Axes, and you get a dictionary of Axes keyed by name. GridSpec does the same with slices, but the mosaic is more readable. See GridSpec and subplot_mosaic.

Python Q8: a spanning panel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 3: Saving, size and dpi

Q9. How do figsize and dpi relate to the size of a saved image?

figsize is the size in inches, dpi is dots (pixels) per inch, and the pixel size is their product: a (6, 4) figure at 100 dpi is 600 by 400 pixels. Raising dpi makes a sharper raster with the same layout; changing figsize changes the layout proportions (text becomes relatively smaller on a larger figure). For vector formats (SVG, PDF) dpi mostly does not matter, because nothing is rasterized. See Saving Figures.

Python Q9: size, dpi and bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q10. A saved figure has its labels cut off. How do you fix it?

The saved canvas is exactly the figure rectangle, so anything outside it is clipped. Use fig.savefig(..., bbox_inches="tight") to expand or trim the saved area to fit all the artists, or use layout="constrained" when creating the figure so the layout makes room for labels in the first place. Add pad_inches for a margin.

Q11. When would you save as SVG or PDF instead of PNG?

Use a vector format when the figure will be scaled, printed or edited: papers, slides, posters, logos. They stay sharp at any size, and text remains text. Use PNG for web pages and when the figure has huge numbers of points, because a vector file stores every point and can become enormous. Add transparent=True for a see-through background.

Part 4: Performance and memory

Q12. How would you plot a few million points?

Do not draw them one by one. Options, from simplest: (1) aggregate before plotting, with hist2d or hexbin for densities and hist for distributions; (2) downsample or decimate, keeping every n-th point or the min and max in each bucket so peaks survive; (3) draw with rasterized=True so a vector file stores one image instead of millions of shapes; (4) use small markers and ax.plot with "," or "." instead of scatter, which is slower because it builds a per-point collection; (5) set plt.rcParams["agg.path.chunksize"] for very long lines. See Plotting Large Data Fast.

Python Q12: aggregate instead of drawing everything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q13. Your script generates many figures and memory keeps growing. Why?

pyplot keeps a reference to every open figure until you close it, so a loop that creates figures without closing them leaks memory (and Matplotlib warns after 20 open figures). Close each figure when you are done: plt.close(fig), or plt.close("all"). When generating charts in a loop, prefer creating the figure with plt.subplots, saving, and closing, as covered in Reproducible and Automated Charts.

Python Q13: leaking figures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q14. Why can scatter be slower than plot?

ax.plot makes one Line2D with all the points and a single marker style. ax.scatter makes a PathCollection that can give every point its own size and color, which costs more per point. If all the points look the same, use plot(x, y, "o"). Use scatter when size or color encodes data.

Part 5: Backends and environment

Q15. What is a backend?

A backend is the code that turns a figure into pixels or a file and (for interactive backends) a window. Non-interactive backends write files: Agg (PNG raster), SVG, PDF. Interactive backends open windows or widgets: QtAgg, TkAgg, macosx, webagg, and in notebooks inline or ipympl. Servers and tests should use Agg, which needs no display. You choose the backend with the MPLBACKEND environment variable, matplotlib.use("Agg") before importing pyplot, or the rc file.

Python Q15: which backend is running?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Q16. Why does plt.show() do nothing on a server?

With a non-interactive backend such as Agg there is no window to show, so plt.show() returns immediately (and may warn). On servers you call fig.savefig(...) instead. See Interactivity and Widgets.

Part 6: Choosing and designing charts

Q17. How do you choose the right chart?

Start from the question. Trend over time: line chart. Compare categories: bar chart (horizontal for long names, sorted). Distribution of one variable: histogram, box or violin plot. Relationship between two numbers: scatter plot, with a fitted line if useful. Parts of a whole: a stacked bar or a donut for very few parts; pies are hard to read for more than three or four. Two variables across many categories: heatmap. Then remove clutter and label directly. See Designing Clear Charts.

Q18. Why is a truncated y axis on a bar chart a problem?

Bar length encodes the value, so the bar must start at zero. Cutting the axis makes small differences look huge. A line chart or dot plot does not encode value in length, so a non-zero baseline is acceptable there if clearly labeled.

Q19. How do you make a chart accessible?

Do not rely on color alone: vary line styles or markers, label lines directly, and choose colorblind-safe palettes (viridis, or the Okabe-Ito colors for categories). Use sufficient contrast and large enough text. Provide alt text or a caption for the image when you publish it, and a table of the data where it matters.

Q20. How do you give one chart a consistent look across a whole report?

Put the style in one place: a style file for plt.style.use, a dictionary applied with plt.rc_context, or a helper function that creates a configured figure. Use the same fonts, palette and sizes everywhere. See Styles, rcParams and Themes. Here is a mini version of the pattern, checked so the style does not leak:

Python Q20: a style that does not leak

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You call plt.plot([1, 2, 3]) after creating two figures with plt.subplots(). Where does the line go?

    pyplot applies bare calls to the current figure and current Axes, which are the most recent ones. This hidden state is why the OO style (ax.plot) is safer in non-trivial code.
  2. 2. A figure is 6 by 4 inches and saved at dpi=200 as a PNG. How many pixels is it?

    Pixel size equals inches times dpi: 6 * 200 = 1200 and 4 * 200 = 800.
  3. 3. Which approach best handles plotting 5 million scatter points?

    Millions of individual artists are slow and unreadable. Aggregating into cells shows the density, and downsampling reduces the number of drawn objects.
  4. 4. Why should loops that create many figures call plt.close(fig)?

    Open figures stay registered with pyplot until closed. A long loop without closing leaks memory and eventually triggers a warning.
  5. 5. What is the difference between Axes and Axis?

    A Figure contains Axes (plots); each 2D Axes owns an xaxis and a yaxis, which are Axis objects managing ticks, tick labels and scales.

Summary

  • Know the hierarchy: Figure contains Axes; an Axes owns two Axis objects; everything drawn is an Artist.
  • Prefer the OO API; pyplot's hidden "current" state is the source of many bugs.
  • Pixel size is figsize times dpi; vector formats stay sharp; bbox_inches="tight" or constrained layout prevents clipped labels.
  • Share axes for honest comparison; use twinx sparingly; subplot_mosaic builds dashboards.
  • For big data, aggregate, downsample or rasterize; close figures in loops.
  • Backends turn figures into pixels; servers use Agg and savefig.
  • Choose the chart from the question, start bars at zero, and keep styles in one place.

Finish with the one-page Matplotlib Cheat Sheet.