Matplotlib · Chapter 3 of 16

Showing and saving

By the end of this chapter you can say where a chart is shown (the backend), set a figure's size in inches and its resolution in dots per inch and work out its pixels, save it as a PNG, an SVG or a PDF and measure each file, crop it to what is drawn, save it into memory instead of a file, and close the figures you no longer need. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The first chart
  • 4 tasks
  • Matplotlib
  • In the all labs plan

The first 2 chapters of Matplotlib are free. This one comes with the all labs plan.

Why you need this

Every chart so far has been 640 by 480 pixels, because that is what a new figure is. SaafHawa's charts now go to four places, and none of them wants that:

  • Ira sends each principal a chart on WhatsApp every morning. A square picture fills a phone's screen; a 640 by 480 one shows up small, with its labels too fine to read.
  • Lalitha emails the monthly report to the housing societies and prints it for their notice boards. A PNG enlarged for print goes soft at the edges.
  • SaafHawa's web page shows the same charts, and the server that builds the page wants a picture's bytes, not a file on its disk.
  • Jaspreet's nightly job saves one chart for each of the 48 stations, and every night Python prints a warning about "More than 20 figures", while the job's memory grows.

All four are about what happens after the drawing: where the chart goes, at what size, in which format, and what is left behind.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    square_chart.py: a square chart for WhatsApp

    Write square_chart(hours, pm25, path) in square_chart.py. hours are the hours of one day, 0 to 23, and pm25 a station's reading at each hour, from diwali_hourly.csv. Make a new Figure and Axes, draw pm25 against hours as one line, save the figure as a PNG at path, and return the Figure.

    The file must be exactly 1080 by 1080 pixels, saved at 200 dpi (lab image shows both). The Check gives paths in another folder, ending in mayur_vihar_square.png and anand vihar square.png, so save at the path it is given. It also looks at what the figure held when it was saved: the line must be on it by then, and the figure returned must be the one saved.

  2. Task 2

    png_and_svg.py: the same chart as a PNG and an SVG

    Write save_both(fig, base) in png_and_svg.py. fig is a finished chart and base is a path without an ending, such as noida_month. Save fig as base + ".png" and as base + ".svg", and return the two files' sizes on disk in bytes, as a tuple of two whole numbers: (the PNG's size, the SVG's size).

    Change nothing about the figure's size or dpi: the PNG must have the figure's own size in pixels. The Check gives a 6 by 3 inch chart (600 by 300 pixels) and a chart of the size a new figure has (640 by 480), with bases in another folder ending in gurugram week and noida_month. It checks that both files are there and hold a PNG and an SVG, that both were saved from the fig it gave, and that the numbers returned are the files' real sizes.

  3. Task 3

    chart_png.py: a chart's PNG without a file

    Write chart_png(fig) in chart_png.py. fig is a finished chart. Save it as a PNG into memory, not to disk, and return the PNG's bytes: a bytes object (not the buffer you saved into), starting with the PNG signature b'\x89PNG\r\n\x1a\n', at the figure's own size in pixels.

    The Check gives a 5 by 3 inch chart (500 by 300 pixels) and a chart of the size a new figure has (640 by 480), checks that no new file appears in this folder, that the bytes are a PNG of the figure's own size, and that they were saved from the fig it gave.

  4. Task 4 · interview question

    Interview: station_files.py, 48 charts and a warning

    Jaspreet's station_charts(readings, folder) saves one chart per station every night. readings is a dict whose keys are station ids, such as "SH-DEL-01", and whose values are (days, pm25): the station's day numbers and daily PM2.5 for the month, from daily.csv. Each chart is saved in folder as <station id>.png, one Axes with one line, titled with the station's id. The files are right, but with 48 stations Python warns "More than 20 figures have been opened", and the job's memory grows.

    Fix it so that every station's file is still saved as before and, when the function ends, pyplot holds no figure open. The Check calls it with 24 stations of September 2026 and then 3 stations of August, reads what each figure held when its file was saved, and then counts the figures pyplot still has open: there must be none.

    Tanvir will ask: why does pyplot keep every figure, what does it cost, and where in the loop does the fix go?

What you will learn

  • The backend: Agg here, a window on a laptop; matplotlib.get_backend().
  • figsize=(w, h) in inches and dpi=: pixels are inches times dots per inch.
  • fig.savefig(name, dpi=...), and formats from the name's ending: PNG, SVG, PDF.
  • bbox_inches="tight", pad_inches, facecolor=, transparent=True.
  • io.BytesIO: a PNG saved into memory, getvalue() for its bytes.
  • plt.close(fig), plt.close("all") and plt.get_fignums().

More in The first chart

Build "Showing and saving" yourself

SaafHawa runs air sensors across Delhi NCR. Principals, societies and investors need its numbers at a glance: you draw them. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Matplotlib are free. This one comes with the all labs plan.