Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 57 ยท Practice and Interview

Practice Exercises With Solutions

Practice Matplotlib with 25 graded exercises on line plots, bars, histograms, subplots, annotations, styling, dates and heatmaps. Every solution runs live.

You learn Matplotlib by drawing with it. This page has 25 exercises, ordered from easy to challenging and grouped by topic. Each one states a task and describes the figure you should end up with, then gives a runnable solution in an editor. The solutions end with assert statements that check properties of the figure itself, such as labels, limits and the number of artists, so a wrong edit fails loudly instead of quietly producing a different picture.

How to use this page

For the best learning, do not run the solution first. Read the task, then write your own answer in a scratch editor (delete the solution body and type yours), run it and compare your picture with the described one. Then compare code. If an exercise takes more than ten minutes, peek at the solution, close it and redo it from memory the next day.

Three habits solve most plotting problems:

  1. Sketch the result first. Decide what is on each axis, what the title says and what the reader should notice.
  2. Use the object-oriented pattern: fig, ax = plt.subplots(...) and then call methods on ax (pyplot vs the Object-Oriented API).
  3. Check the figure, not just the code. Print a few facts (ax.get_xlim(), len(ax.patches)) while you work.
flowchart TD
    A["Read the task"] --> B["Sketch the figure"]
    B --> C["fig, ax = plt.subplots()"]
    C --> D["Draw data"]
    D --> E["Label, limit, style"]
    E --> F{"Does it match<br/>the description?"}
    F -- "no" --> D
    F -- "yes" --> G["Compare with the solution"]

A routine for attacking any plotting exercise.

Part 1: Basic plots

Related lessons: Your First Plot, Line Plots in Depth and Colors, Line Styles and Markers.

Exercise 1. Plot y = x**2 for x from -3 to 3 (100 points). Add the title "Parabola", axis labels "x" and "y = x squared", and a grid. Expected figure: a U-shaped curve with its lowest point at the origin, a title, two labels and light grid lines.

Python Exercise 1: a labeled parabola

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.

Exercise 2. Plot sine and cosine on [0, 2*pi] in one axes: sine as a solid blue line, cosine as a dashed orange line with circle markers on every 20th point. Add a legend. Expected figure: two waves a quarter period apart, the dashed one with markers, a legend naming both.

Python Exercise 2: sine and cosine

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.

Exercise 3. The data below grows exponentially. Plot it so the growth looks like a straight line, and say in the title what the straight line means. Expected figure: points rising on a log-scaled y axis along a straight line.

Python Exercise 3: a log scale

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.

Exercise 4. Draw 12 random points with numpy.random.default_rng(5). Make a scatter plot where the color of each point shows a third variable z using the viridis colormap, with a colorbar labeled "z". Expected figure: scattered points in a purple-to-yellow gradient and a labeled colorbar on the right.

Python Exercise 4: scatter with a colorbar

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.

Exercise 5. Plot sin(x) on [0, 10], then restrict the view to x from 2 to 8 and y from -1.5 to 1.5 without changing the data, and mark where the curve crosses zero inside that range with red dots. Expected figure: a zoomed sine wave with three red dots at x near pi, 2 pi and 3 pi.

Python Exercise 5: limits and markers

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.

The solution to the last one shows something worth remembering: the third crossing at 9.42 lies outside the view, so only two red dots appear. Always check the numbers before you trust the picture.

Part 2: Bars and histograms

Related lessons: Bar Charts and Histograms and Distributions.

Exercise 6. Draw grouped bars comparing two years for four regions. Put a legend and the region names on the x axis. Expected figure: four pairs of side-by-side bars, blue for 2024 and orange for 2025.

Python Exercise 6: grouped bars

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.

Exercise 7. Turn the same data into a stacked bar chart of total sales per region, with the 2025 segment on top of 2024. Expected figure: four bars, each made of two stacked colors, whose heights are the sums.

Python Exercise 7: stacked bars

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.

Exercise 8. Make a horizontal bar chart of the languages below, sorted so the largest bar is on top, with the value printed at the end of each bar using bar_label. Expected figure: five horizontal bars decreasing from top to bottom with numbers at their ends.

Python Exercise 8: sorted horizontal bars

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.

Exercise 9. The histogram below uses the default 10 bins. Redraw it with bin edges every 5 units from 40 to 100, mark the mean with a vertical dashed line and label it. Expected figure: a bell-shaped histogram with 12 bars and a dashed line near 70.

Python Exercise 9: bins and a mean line

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.

Exercise 10. Compare two samples with overlaid, translucent histograms drawn on the same bins and normalized to density, so different sample sizes can be compared. Expected figure: two overlapping bell shapes in different colors, the wider one lower.

Python Exercise 10: overlaid densities

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: Subplots and layouts

Related lessons: Multiple Subplots, GridSpec and subplot_mosaic and Shared, Twin and Secondary Axes.

Exercise 11. Make a 2 by 2 grid showing sin, cos, tan (limited to y between -5 and 5) and exp(-x), with a shared x axis and one overall title. Only the bottom row should show x tick labels. Expected figure: four small plots, aligned columns, a suptitle.

Python Exercise 11: a shared-axis grid

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.

Exercise 12. Use subplot_mosaic to build a dashboard: a wide line chart on top ("line"), and below it a bar chart ("bar") on the left and a histogram ("hist") on the right. Fill all three with any data. Expected figure: one panel across the top and two side by side beneath it.

Python Exercise 12: a mosaic dashboard

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.

Exercise 13. Plot temperature (degrees C, a line) and rainfall (mm, bars) for six months on the same x axis with twinx. Color each axis label to match its data. Expected figure: bars with a left axis in blue and a line with a right axis in red.

Python Exercise 13: two y axes

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.

Exercise 14. Draw a noisy sine curve and add an inset axes in the upper right that zooms into x between 4 and 5. Draw a box on the main axes showing the zoomed region. Expected figure: a large curve with a small zoomed plot in its corner and a rectangle on the curve.

Python Exercise 14: an inset zoom

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 4: Annotation

Related lessons: Annotations and Arrows and Text and Labels.

Exercise 15. Plot the curve below and annotate its maximum with the text "peak" and an arrow, computing the location from the data with argmax. Expected figure: a hump with an arrow pointing at the top, labeled with the peak's value.

Python Exercise 15: annotate the peak

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.

Exercise 16. Add three reference marks to a line chart: a horizontal dashed line at the average, a vertical line at x = 15, and a shaded band for x between 5 and 10. Expected figure: a wiggly line with a dashed horizontal line, one vertical line and a translucent vertical stripe.

Python Exercise 16: reference lines and spans

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.

Exercise 17. Label the last point of each of three lines directly with its series name, to the right of the line's end, and remove the legend. Expected figure: three lines with names written at their right ends, and no legend box.

Python Exercise 17: direct labels

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 5: Styling

Related lessons: Styles, rcParams and Themes and Ticks, Locators and Formatters.

Exercise 18. Draw the same line twice in two panels: once with the default style, once inside plt.rc_context that sets font.size to 14, axes.spines.top and axes.spines.right to False, and lines.linewidth to 3. The setting must not leak to later figures. Expected figure: a plain plot and a bigger, cleaner one.

Python Exercise 18: rc_context

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.

Exercise 19. Change the color cycle of one axes to four custom colors using a cycler, then plot four offset sine waves without giving any color explicitly. Expected figure: four waves colored with your palette in order.

Python Exercise 19: a custom color cycle

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.

Exercise 20. The y values below are fractions. Format the y tick labels as percentages with no decimals and the x tick labels as Q1 ... Q4. Expected figure: a line with y labels such as 20%, 40% and x labels Q1 to Q4.

Python Exercise 20: tick formatters

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 6: Dates and time series

Related lessons: Dates and Time Series Charts.

Exercise 21. Plot 120 days of a random-walk series starting on 2025-01-01 with readable date labels: a tick at the start of each month, labeled like Jan, Feb. Expected figure: a line with month names along the bottom.

Python Exercise 21: a date axis

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.

Exercise 22. On the same data, draw the raw series faintly and a 14-day rolling average boldly on top, then shade the month of March. Expected figure: a faint noisy line, a smooth strong one, and a shaded March band.

Python Exercise 22: rolling average and a shaded month

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 7: Heatmaps and finishing

Related lessons: Heatmaps and Images, Saving Figures.

Exercise 23. Build a 5 by 5 multiplication-table style matrix (np.outer) and show it as a heatmap with the value written in each cell, a colorbar, and tick labels 1 to 5 on both axes. Expected figure: a grid of squares getting brighter toward the lower-right corner with numbers in every cell.

Python Exercise 23: an annotated heatmap

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.

Exercise 24. Draw filled contours of f(x, y) = x * exp(-x**2 - y**2) on a grid from -2 to 2, with black contour lines on top and a colorbar. Use a diverging colormap centered on zero. Expected figure: a red blob on the right and a blue blob on the left, separated by a neutral band.

Python Exercise 24: filled contours

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.

Exercise 25. Save any figure as a PNG at 150 dpi into an in-memory buffer, check that the buffer starts with the PNG signature, and report the pixel size computed from figsize and dpi. Expected output: a figure of 600 by 450 pixels and a confirmation line.

Python Exercise 25: save to a buffer

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.

bbox_inches="tight" trims empty margins, so the saved file may be a little smaller than figsize * dpi; leave it out when you need an exact pixel size.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the grouped bar exercise, why are the bar positions shifted by plus and minus half the bar width?

    Both bar calls use the same group positions, so without the offsets they would overlap. Shifting one left and one right by half a width puts them next to each other around the tick.
  2. 2. What does the bottom argument do in a stacked bar chart?

    bottom is the y value where each new bar starts. Passing the previous series makes the new bars stack on top of it.
  3. 3. Why use plt.rc_context for a temporary style instead of changing plt.rcParams directly?

    rc_context restores the previous settings when the block ends. Direct assignments to rcParams persist until you reset them, which is a classic source of state leaks.
  4. 4. Why does the percent formatter exercise need PercentFormatter(xmax=1)?

    PercentFormatter multiplies by 100 / xmax. The default xmax is 100, so with fractional data you must set xmax=1 or 0.27 would be shown as 0%.
  5. 5. A figure is 4 by 3 inches. How many pixels wide is a PNG saved at dpi=150 without bbox_inches="tight"?

    Pixels equal inches times dpi: 4 * 150 = 600 wide and 3 * 150 = 450 tall.

Summary

  • Work object-oriented: fig, ax = plt.subplots(), then draw, label, limit and style through ax.
  • Bars: offset for groups, bottom for stacks, sort before plotting, bar_label for values; histograms: choose bin edges deliberately and normalize with density=True to compare samples.
  • Layouts: subplots with sharing for grids, subplot_mosaic for dashboards, twinx for two units, inset_axes for zoom.
  • Annotate with annotate computed from the data; use axhline, axvline and axvspan for reference marks.
  • Style locally with rc_context and cycler; format ticks with PercentFormatter and FuncFormatter.
  • Heatmaps need annotations and a colorbar; saving to a buffer lets you inspect output without touching the disk.

Keep going with the Interview Questions.