{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"plotting-with-matplotlib","title":"matplotlib: a plot you can read, saved to a file, from a script or a server","url":"https://addaly.com/learn/python-for-ai/plotting-with-matplotlib","position":78,"of":89,"minutes":8,"answer":"Make a figure and axes with subplots, draw on the axes, label them, and savefig: plt.show() is for a notebook, a log-scaled axis is what makes a loss curve or a token histogram legible.","keyIdea":"Make a figure and axes with subplots, draw on the axes, label them, and savefig: plt.show() is for a notebook, a log-scaled axis is what makes a loss curve or a token histogram legible, and a plot with no axis labels is a plot nobody can check."},"body":{"format":"markdown","text":"## The two-object model\n\nmatplotlib has two ways of being used, and most confusion comes from mixing them. The quick way, `plt.plot(x, y)`, draws on an implicit \"current figure\". The explicit way creates the objects and draws on them by name:\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(8, 4))\nax.plot(steps, loss)\nax.set_xlabel(\"training step\")\nax.set_ylabel(\"loss\")\nax.set_title(\"Loss per step\")\nfig.savefig(\"loss.png\", dpi=150, bbox_inches=\"tight\")\n```\n\n`fig` is the canvas; `ax` is a set of axes on it. Everything you draw goes through `ax`; everything about the file goes through `fig`. Learn this form and the implicit one will still make sense when you read it in other people's code, while the reverse is not true.\n\n`bbox_inches=\"tight\"` stops the labels being cut off at the edge, which is otherwise the first thing that goes wrong.\n\n## The plots you will actually make\n\n**A line over time or steps**: a loss curve, cost per day:\n\n```python\nax.plot(steps, loss, label=\"train\")\nax.plot(steps, val_loss, label=\"validation\")\nax.legend()\n```\n\n**A histogram**: token counts per message, latencies:\n\n```python\nax.hist(tokens, bins=50)\nax.set_xlabel(\"tokens per message\")\n```\n\n**A scatter**: two quantities per item, looking for a relationship:\n\n```python\nax.scatter(prompt_tokens, latency_s, s=8, alpha=0.4)\n```\n\n`s` is marker size and `alpha` is transparency; both matter at a few thousand points, where solid dots become a blob.\n\n**A bar chart**: a number per category, from a groupby:\n\n```python\nby_model = df.groupby(\"model\")[\"cost_usd\"].sum().sort_values()\nax.barh(by_model.index, by_model.values)\n```\n\nHorizontal bars fit long category names. Sort before plotting; an unsorted bar chart hides the ranking it exists to show.\n\npandas wraps all of these: `df[\"tokens\"].plot.hist(bins=50, ax=ax)` and `by_model.plot.barh(ax=ax)` draw onto the axes you pass, so you can mix the convenience with the control.\n\n## Log scale\n\nLoss falls from 4 to 0.4 to 0.04 over training. On a linear axis the last two-thirds of the run is a flat line at the bottom and you cannot see whether it is still improving. Latencies and token counts have a long tail: most messages are 50 tokens and a few are 5,000, and a linear histogram shows one bar.\n\n```python\nax.set_yscale(\"log\")            # loss curve\nax.set_xscale(\"log\")            # histogram of a long-tailed quantity\nax.hist(tokens, bins=np.logspace(1, 4, 40))   # log-spaced bins to match\n```\n\nReach for a log axis whenever the data spans more than two orders of magnitude. It is the single change that most often turns an unreadable plot into a readable one.\n\n## Several plots in one figure\n\n```python\nfig, axes = plt.subplots(1, 3, figsize=(15, 4))\naxes[0].plot(steps, loss)\naxes[1].hist(tokens, bins=40)\naxes[2].scatter(x, y, s=6)\nfor ax in axes:\n    ax.grid(alpha=0.3)\nfig.tight_layout()\nfig.savefig(\"report.png\", dpi=150)\n```\n\n`subplots(rows, cols)` returns an array of axes. `tight_layout` spaces them so labels do not overlap. When comparing runs, `sharey=True` puts them on the same scale, which is what makes the comparison honest.\n\n## Saving versus showing\n\n`plt.show()` opens a window, or renders inline in a notebook. On a server, in a cron job, in a test, there is no window, and matplotlib either errors about a missing display or hangs waiting for one that will never appear. A script that produces plots should **save** them:\n\n```python\nimport matplotlib\nmatplotlib.use(\"Agg\")           # before importing pyplot: file output only, no display\nimport matplotlib.pyplot as plt\n```\n\n`Agg` is the backend that renders to pixels with no window; it is the right choice for anything not run by a person at a screen. Save PNG for reports and web pages, SVG (`savefig(\"plot.svg\")`) for anything that will be scaled or edited in Inkscape, PDF for print.\n\n`plt.close(fig)` after saving releases memory. A loop that makes a hundred figures without closing them holds a hundred figures and prints a warning about it.\n\n## What makes a plot checkable\n\nAxis labels with units. A title that says what the data is and when it was taken. A legend when there is more than one series. Sensible limits: `ax.set_ylim(0, None)` for a quantity that cannot be negative, so the eye is not tricked by a zoomed baseline. The reader should be able to look at the figure with no surrounding text and know what they are looking at, including you, in a month.\n\nColour is not the way to carry meaning alone; around one in twelve men cannot separate red from green. Use different markers or line styles as well when the series must be distinguished, and the default palette, which was chosen with this in mind.\n\n## Free, and everywhere\n\nmatplotlib is free, runs on a phone under Pydroid or Termux, and is what pandas, seaborn and most scientific Python produce their figures with. `seaborn` adds statistical plots on top of it (a heatmap of a confusion matrix in one call) and `plotly` produces interactive charts for a browser; both are free, and both give you a figure you can still touch through matplotlib's axes.\n\n## Try this now\n\nPlot the cost-per-model bar chart from your groupby, the token histogram from your messages on a log x-axis, and a loss curve from any training log you can find, as three panels in one figure saved to PNG with `Agg`. Then run the script with no display (`DISPLAY= python plot.py` on Linux) to confirm it works headless."},"check":{"question":"A script that plots a loss curve works in a notebook but, run on a headless server by cron, either hangs or logs `no display name and no $DISPLAY environment variable`. What is the fix that addresses the cause?","options":[{"text":"Select the file-only backend with `matplotlib.use(\"Agg\")` before importing pyplot, then `fig.savefig(path)` and no `show()`.","correct":true},{"text":"Install a desktop environment on the server so that the plotting window has somewhere to open, and run the cron job inside a logged-in graphical session.","correct":false,"tempting":"That would work and is wildly out of proportion; the script does not need a window at all."},{"text":"Call `plt.show()` before `savefig` so the figure is rendered into memory first.","correct":false,"tempting":"`show()` is what tries to open a window; calling it earlier moves the failure, not removes it."},{"text":"Run the script with `python -i` so that the interactive interpreter provides the display.","correct":false,"tempting":"`-i` keeps the interpreter open afterwards; it provides no display, and the error is about the absence of one."}]},"prev":{"slug":"groupby-merge-and-reshape","title":"groupby, merge and pivot: getting from rows to the table a question needs","url":"https://addaly.com/learn/python-for-ai/groupby-merge-and-reshape"},"next":{"slug":"notebooks-without-hidden-state","title":"Notebooks without hidden state: execution order, restart-and-run-all, and when to leave for a .py file","url":"https://addaly.com/learn/python-for-ai/notebooks-without-hidden-state"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'matplotlib: a plot you can read, saved to a file, from a script or a server', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/plotting-with-matplotlib (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"matplotlib: a plot you can read, saved to a file, from a script or a server","courseTitle":"Python, from Zero, for AI","module":{"index":8,"slug":"numbers-in-bulk","title":"Numbers in bulk: NumPy, pandas and the vector under every model"},"answer":null,"keyIdea":"Make a figure and axes with subplots, draw on the axes, label them, and savefig: plt.show() is for a notebook, a log-scaled axis is what makes a loss curve or a token histogram legible, and a plot with no axis labels is a plot nobody can check.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-two-object-model","runs":[{"text":"The two-object model"}]},{"t":"p","runs":[{"text":"matplotlib has two ways of being used, and most confusion comes from mixing them. The quick way, "},{"text":"plt.plot(x, y)","code":true},{"text":", draws on an implicit “current figure”. The explicit way creates the objects and draws on them by name:"}]},{"t":"code","lang":"python","label":"Python","text":"import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(8, 4))\nax.plot(steps, loss)\nax.set_xlabel(\"training step\")\nax.set_ylabel(\"loss\")\nax.set_title(\"Loss per step\")\nfig.savefig(\"loss.png\", dpi=150, bbox_inches=\"tight\")"},{"t":"p","runs":[{"text":"fig","code":true},{"text":" is the canvas; "},{"text":"ax","code":true},{"text":" is a set of axes on it. Everything you draw goes through "},{"text":"ax","code":true},{"text":"; everything about the file goes through "},{"text":"fig","code":true},{"text":". Learn this form and the implicit one will still make sense when you read it in other people’s code, while the reverse is not true."}]},{"t":"p","runs":[{"text":"bbox_inches=\"tight\"","code":true},{"text":" stops the labels being cut off at the edge, which is otherwise the first thing that goes wrong."}]},{"t":"h2","id":"the-plots-you-will-actually-make","runs":[{"text":"The plots you will actually make"}]},{"t":"p","runs":[{"text":"A line over time or steps","b":true},{"text":": a loss curve, cost per day:"}]},{"t":"code","lang":"python","label":"Python","text":"ax.plot(steps, loss, label=\"train\")\nax.plot(steps, val_loss, label=\"validation\")\nax.legend()"},{"t":"p","runs":[{"text":"A histogram","b":true},{"text":": token counts per message, latencies:"}]},{"t":"code","lang":"python","label":"Python","text":"ax.hist(tokens, bins=50)\nax.set_xlabel(\"tokens per message\")"},{"t":"p","runs":[{"text":"A scatter","b":true},{"text":": two quantities per item, looking for a relationship:"}]},{"t":"code","lang":"python","label":"Python","text":"ax.scatter(prompt_tokens, latency_s, s=8, alpha=0.4)"},{"t":"p","runs":[{"text":"s","code":true},{"text":" is marker size and "},{"text":"alpha","code":true},{"text":" is transparency; both matter at a few thousand points, where solid dots become a blob."}]},{"t":"p","runs":[{"text":"A bar chart","b":true},{"text":": a number per category, from a groupby:"}]},{"t":"code","lang":"python","label":"Python","text":"by_model = df.groupby(\"model\")[\"cost_usd\"].sum().sort_values()\nax.barh(by_model.index, by_model.values)"},{"t":"p","runs":[{"text":"Horizontal bars fit long category names. Sort before plotting; an unsorted bar chart hides the ranking it exists to show."}]},{"t":"p","runs":[{"text":"pandas wraps all of these: "},{"text":"df[\"tokens\"].plot.hist(bins=50, ax=ax)","code":true},{"text":" and "},{"text":"by_model.plot.barh(ax=ax)","code":true},{"text":" draw onto the axes you pass, so you can mix the convenience with the control."}]},{"t":"h2","id":"log-scale","runs":[{"text":"Log scale"}]},{"t":"p","runs":[{"text":"Loss falls from 4 to 0.4 to 0.04 over training. On a linear axis the last two-thirds of the run is a flat line at the bottom and you cannot see whether it is still improving. Latencies and token counts have a long tail: most messages are 50 tokens and a few are 5,000, and a linear histogram shows one bar."}]},{"t":"code","lang":"python","label":"Python","text":"ax.set_yscale(\"log\")            # loss curve\nax.set_xscale(\"log\")            # histogram of a long-tailed quantity\nax.hist(tokens, bins=np.logspace(1, 4, 40))   # log-spaced bins to match"},{"t":"p","runs":[{"text":"Reach for a log axis whenever the data spans more than two orders of magnitude. It is the single change that most often turns an unreadable plot into a readable one."}]},{"t":"h2","id":"several-plots-in-one-figure","runs":[{"text":"Several plots in one figure"}]},{"t":"code","lang":"python","label":"Python","text":"fig, axes = plt.subplots(1, 3, figsize=(15, 4))\naxes[0].plot(steps, loss)\naxes[1].hist(tokens, bins=40)\naxes[2].scatter(x, y, s=6)\nfor ax in axes:\n    ax.grid(alpha=0.3)\nfig.tight_layout()\nfig.savefig(\"report.png\", dpi=150)"},{"t":"p","runs":[{"text":"subplots(rows, cols)","code":true},{"text":" returns an array of axes. "},{"text":"tight_layout","code":true},{"text":" spaces them so labels do not overlap. When comparing runs, "},{"text":"sharey=True","code":true},{"text":" puts them on the same scale, which is what makes the comparison honest."}]},{"t":"h2","id":"saving-versus-showing","runs":[{"text":"Saving versus showing"}]},{"t":"p","runs":[{"text":"plt.show()","code":true},{"text":" opens a window, or renders inline in a notebook. On a server, in a cron job, in a test, there is no window, and matplotlib either errors about a missing display or hangs waiting for one that will never appear. A script that produces plots should "},{"text":"save","b":true},{"text":" them:"}]},{"t":"code","lang":"python","label":"Python","text":"import matplotlib\nmatplotlib.use(\"Agg\")           # before importing pyplot: file output only, no display\nimport matplotlib.pyplot as plt"},{"t":"p","runs":[{"text":"Agg","code":true},{"text":" is the backend that renders to pixels with no window; it is the right choice for anything not run by a person at a screen. Save PNG for reports and web pages, SVG ("},{"text":"savefig(\"plot.svg\")","code":true},{"text":") for anything that will be scaled or edited in Inkscape, PDF for print."}]},{"t":"p","runs":[{"text":"plt.close(fig)","code":true},{"text":" after saving releases memory. A loop that makes a hundred figures without closing them holds a hundred figures and prints a warning about it."}]},{"t":"h2","id":"what-makes-a-plot-checkable","runs":[{"text":"What makes a plot checkable"}]},{"t":"p","runs":[{"text":"Axis labels with units. A title that says what the data is and when it was taken. A legend when there is more than one series. Sensible limits: "},{"text":"ax.set_ylim(0, None)","code":true},{"text":" for a quantity that cannot be negative, so the eye is not tricked by a zoomed baseline. The reader should be able to look at the figure with no surrounding text and know what they are looking at, including you, in a month."}]},{"t":"p","runs":[{"text":"Colour is not the way to carry meaning alone; around one in twelve men cannot separate red from green. Use different markers or line styles as well when the series must be distinguished, and the default palette, which was chosen with this in mind."}]},{"t":"h2","id":"free-and-everywhere","runs":[{"text":"Free, and everywhere"}]},{"t":"p","runs":[{"text":"matplotlib is free, runs on a phone under Pydroid or Termux, and is what pandas, seaborn and most scientific Python produce their figures with. "},{"text":"seaborn","code":true},{"text":" adds statistical plots on top of it (a heatmap of a confusion matrix in one call) and "},{"text":"plotly","code":true},{"text":" produces interactive charts for a browser; both are free, and both give you a figure you can still touch through matplotlib’s axes."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Plot the cost-per-model bar chart from your groupby, the token histogram from your messages on a log x-axis, and a loss curve from any training log you can find, as three panels in one figure saved to PNG with "},{"text":"Agg","code":true},{"text":". Then run the script with no display ("},{"text":"DISPLAY= python plot.py","code":true},{"text":" on Linux) to confirm it works headless."}]}],"check":{"question":[{"text":"A script that plots a loss curve works in a notebook but, run on a headless server by cron, either hangs or logs "},{"text":"no display name and no $DISPLAY environment variable","code":true},{"text":". What is the fix that addresses the cause?"}],"options":[{"text":[{"text":"Select the file-only backend with "},{"text":"matplotlib.use(\"Agg\")","code":true},{"text":" before importing pyplot, then "},{"text":"fig.savefig(path)","code":true},{"text":" and no "},{"text":"show()","code":true},{"text":"."}],"correct":true,"tempting":null},{"text":[{"text":"Install a desktop environment on the server so that the plotting window has somewhere to open, and run the cron job inside a logged-in graphical session."}],"correct":false,"tempting":[{"text":"That would work and is wildly out of proportion; the script does not need a window at all."}]},{"text":[{"text":"Call "},{"text":"plt.show()","code":true},{"text":" before "},{"text":"savefig","code":true},{"text":" so the figure is rendered into memory first."}],"correct":false,"tempting":[{"text":"show()","code":true},{"text":" is what tries to open a window; calling it earlier moves the failure, not removes it."}]},{"text":[{"text":"Run the script with "},{"text":"python -i","code":true},{"text":" so that the interactive interpreter provides the display."}],"correct":false,"tempting":[{"text":"-i","code":true},{"text":" keeps the interpreter open afterwards; it provides no display, and the error is about the absence of one."}]}],"order":[2,0,3,1],"why":null},"prev":{"slug":"groupby-merge-and-reshape","title":"groupby, merge and pivot: getting from rows to the table a question needs","minutes":9},"next":{"slug":"notebooks-without-hidden-state","title":"Notebooks without hidden state: execution order, restart-and-run-all, and when to leave for a .py file","minutes":8}}}