Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 149 ยท Data and the Web

Plotting with Matplotlib

Learn Matplotlib step by step. Draw line, bar, scatter, histogram and pie charts, add labels and legends, build subplots, apply styles and save figures.

Numbers in a table tell you what happened; a chart shows you the shape of it in one glance. A trend, an outlier, two groups that barely overlap: you spot them in a plot long before you'd find them in a column of figures. Matplotlib is Python's standard plotting library. It draws almost any static chart you can think of, and the higher-level tools you'll meet later, such as pandas' .plot() and Seaborn, are built on top of it.

In this lesson you'll learn the two ways to use Matplotlib (the quick pyplot style and the object-oriented fig, ax style), draw the five chart types you'll use most, label everything properly, put several plots in one figure, change the look with styles and save your work to a file. You should be comfortable with NumPy arrays first; pandas helps for the last sections.

Note: Matplotlib is a third-party package (pip install matplotlib on your own computer). The editors here load it automatically, and every figure appears as an image in the output when the code calls plt.show(). The first Run downloads Matplotlib and NumPy, so give it a few seconds; later runs are quick.

Your first plot

The usual import is import matplotlib.pyplot as plt. pyplot is a collection of functions that draw on "the current figure", creating one for you when needed. Give plt.plot() a list of x values and a list of y values, and it connects the points with a line:

Python A first line chart

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.

plt.show() displays the figure. In a normal script it opens a window and waits until you close it; in a Jupyter notebook the figure appears below the cell; here it appears as an image under the code. If you pass only one list, as in plt.plot(visitors), Matplotlib uses the positions 0, 1, 2โ€ฆ as the x values.

Figures and axes: the object-oriented style

The quick style is fine for one chart, but it hides two objects you should know about:

  • A Figure is the whole image: the canvas, its size and everything on it.
  • An Axes (note the "es") is one plot inside the figure: the area with the x and y axis, the data, the title and the legend. A figure can hold many axes.

plt.subplots() creates both at once and hands them to you. You then call methods on the axes object. Most methods have the same names as the pyplot functions; the setters gain a set_ prefix:

Python fig, ax = plt.subplots()

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.

figsize=(7, 3.5) sets the size in inches (width, height). The keyword arguments to plot() control the look: color (a name like "tab:orange" or a hex code like "#1f77b4"), linewidth, linestyle ("-", "--", ":"), marker ("o", "s", "^") and markersize.

Which style should you use? Use fig, ax for anything you'll keep. It's explicit about which plot you're drawing on, so it scales to several subplots and to functions that take an ax argument. Use plain plt. calls for throwaway checks. Mixing both in one script is common and works, as long as you remember that plt.title() acts on the current axes and ax.set_title() on the one you name.

The five chart types you'll use most

Each chart type answers a different question. Pick the chart for the question, not the other way round:

Chart Method Best for
Line ax.plot(x, y) A value changing over an ordered axis, usually time
Bar ax.bar(names, values) / ax.barh() Comparing amounts across categories
Scatter ax.scatter(x, y) The relationship between two numeric variables
Histogram ax.hist(values, bins=...) How one variable's values are distributed
Pie ax.pie(values, labels=...) Parts of one whole, with very few parts

Bar charts

Bars compare categories. Use bar() for vertical bars and barh() for horizontal ones, which leave more room for long labels. bar_label() writes the value on each bar:

Python Bar and horizontal bar charts

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 horizontal version reverses the lists because barh() draws the first item at the bottom. fig.tight_layout() nudges the plots so titles and labels don't overlap.

Scatter plots and histograms

A scatter plot draws one dot per pair of values, so a cloud that rises from left to right means "bigger x tends to go with bigger y". The c= argument can color each dot by a third value, and alpha makes overlapping dots see-through. A histogram sorts one list of numbers into bins and draws how many values fall in each one:

Python Scatter plot and histogram

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.

Try changing bins=10 to bins=4 and then bins=30. Too few bins hide the shape; too many make it noisy. axvline() and its sibling axhline() draw a reference line across the whole plot, which is handy for marking a mean, a target or a threshold. A colormap (cmap) such as "viridis" turns numbers into colors, and fig.colorbar() adds the key that explains them.

Pie charts

A pie chart shows how one whole splits into parts. It only works with a handful of slices, because people judge angles far less accurately than lengths. When in doubt, a bar chart is clearer. If you do use one, autopct prints the percentages:

Python A simple pie chart

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.

autopct="%1.0f%%" is an old-style format string: a number with no decimals followed by a literal % (written %%). startangle=90 starts the first slice at the top instead of on the right.

Labels, legends and annotations

A chart without labels makes the reader guess. Every chart you share should have a title, labeled axes with units, and a legend whenever more than one series is shown. Give each series a label=, then call ax.legend():

Python Legends, limits and annotations

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.

  • ax.set(...) sets several properties in one call: title, xlabel, ylabel, xlim, ylim and so on.
  • set_xlim() / set_ylim() fix the visible range. Starting a bar chart's y axis at zero keeps the bar lengths honest; a line chart may zoom in.
  • legend(loc="upper left") places the legend; the default loc="best" picks a spot that hides the least data.
  • annotate() writes text at xytext with an arrow pointing at the data point xy. Both use data coordinates.

Several plots in one figure

You've already seen plt.subplots(1, 2). In general plt.subplots(rows, cols) returns a figure and a NumPy array of axes with that shape, so you can loop over them. sharex=True or sharey=True makes the plots use the same scale, which makes them easier to compare:

Python A grid of subplots

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.

axes.flat walks through the grid row by row, so one loop fills every plot. fig.suptitle() gives the whole figure a title above the individual ones. Use axes[0, 1] when you need one specific plot (row 0, column 1).

Styles

A style sheet changes colors, fonts, grid lines and backgrounds for every plot at once. plt.style.available lists the built-in ones. Use plt.style.use("ggplot") to switch for the rest of the script, or with plt.style.context(...) to apply a style to just the plots made inside the block:

Python Comparing style sheets

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.

That example makes three figures, and plt.show() displays all of them in order. Styles named seaborn-v0_8-... copy the look of the Seaborn library without needing it installed. For one-off changes you can also edit plt.rcParams, the dictionary of defaults, for example plt.rcParams["font.size"] = 12.

Saving figures

fig.savefig() writes the figure to a file. The file extension picks the format:

  • PNG for screens, slides and web pages. Raise dpi (dots per inch) for sharper images.
  • SVG or PDF for print and documents. They're vector formats, so they stay crisp at any zoom.

On your own computer, saving a sharp PNG is one line:

Python
fig.savefig("chart.png", dpi=150, bbox_inches="tight")

The editor below saves the vector formats instead. (The browser build of Matplotlib prints a harmless deprecation warning when it writes PNG files, which would only distract here.)

Python savefig() to SVG and PDF

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 the empty margin around the chart. Call savefig() before plt.show(): in a normal script, closing the window that show() opens also discards the figure, and saving afterwards gives you an empty image. In a script that makes hundreds of charts, plt.close(fig) after saving frees memory. The files here live in the editor's temporary in-memory file system, so the code just proves they exist by reading the first bytes back.

Plotting straight from pandas

DataFrames and Series have a .plot() method that calls Matplotlib for you, using the index as the x axis and column names as legend labels. kind= picks the chart type ("line", "bar", "barh", "hist", "scatter", "pie", "box"), and it returns the axes, so you can keep customizing:

Python DataFrame.plot()

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.

Passing ax= tells pandas which subplot to draw on, so you can mix pandas plots with your own. For quick exploration, a bare df.plot() followed by plt.show() is often all you need. In the editors here, import matplotlib.pyplot yourself in pandas examples, since that's what loads Matplotlib.

Seaborn: statistical plots in one line

Seaborn is a popular library on top of Matplotlib for statistical charts. It works directly with DataFrames: you name the columns and it handles grouping, colors and legends. Seaborn isn't available in the in-browser editors, so here's a read-only taste of what it looks like on your own computer (pip install seaborn):

Python
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")   # a small sample dataset (downloaded on first use)

sns.set_theme()                   # Seaborn's default look for all plots
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
plt.show()

sns.boxplot(data=tips, x="day", y="total_bill")
plt.show()

sns.histplot(data=tips, x="total_bill", hue="sex", kde=True)
plt.show()

Each Seaborn function returns a normal Matplotlib axes, so everything in this lesson (set_title(), set_xlim(), savefig()) still applies. A good rule of thumb: reach for Seaborn when you're exploring a dataset and want grouped statistical plots fast; use plain Matplotlib when you need full control over a specific chart.

Tip: Matplotlib makes static images. For interactive charts in a browser (zoom, hover tooltips), look at libraries such as Plotly or Bokeh. The ideas you learned here, figures, axes, labels and chart choice, carry over directly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fig, ax = plt.subplots() give you?

    The Figure is the canvas; the Axes is the plot area you draw on with methods such as ax.plot() and ax.set_title().
  2. 2. You want to show how 500 exam scores are spread out. Which chart fits best?

    A histogram groups one variable's values into bins and shows how many fall in each, which is exactly a distribution.
  3. 3. A plot has two lines created with label="A" and label="B", but no legend appears. What is missing?

    Labels are stored with each series, but the legend box is only drawn when you call ax.legend() (or plt.legend()).
  4. 4. What is the shape of axes after fig, axes = plt.subplots(2, 3)?

    With more than one row and column you get a 2-D NumPy array of axes with shape (rows, cols); axes.flat iterates over all six.
  5. 5. Why should fig.savefig("chart.png") come before plt.show() in a script?

    Once the figure window is closed the figure is gone, so save first and then show.

Summary

  • import matplotlib.pyplot as plt; draw, label, then plt.show().
  • A Figure is the whole image; an Axes is one plot. fig, ax = plt.subplots() gives you both, and the ax. methods are the clearest way to build real charts.
  • Line for trends, bar for categories, scatter for relationships, histogram for distributions, pie only for a few parts of a whole.
  • Always add a title, axis labels with units, and a legend (label= + ax.legend()) when there's more than one series. annotate(), axhline() and axvline() point out what matters.
  • plt.subplots(rows, cols) returns an array of axes; loop over axes.flat, share scales with sharex/sharey, and finish with fig.tight_layout().
  • Change the look with plt.style.use() or plt.style.context(), save with fig.savefig("name.png", dpi=150, bbox_inches="tight") before showing.
  • pandas' df.plot(kind=...) and Seaborn build on Matplotlib, so the same axes methods work on their charts.

Next: Machine Learning with scikit-learn, where you'll teach a computer to make predictions from data like the data you just plotted.