Matplotlib Basics

Matplotlib Basics

1Matplotlib Basics: overview

Matplotlib is Python's main charting library: you give it lists or arrays of numbers, choose a chart type, add labels, and it draws the figure for you.

GoalBy the end you can draw line, bar and scatter charts, add a title, axis labels and a legend, and place several charts side by side with subplots.

Before this lesson: Python Lists, NumPy Basics

2Matplotlib Basics: diagram

Matplotlib Basicsdata: x and y listsfig, ax = plt.subplots()create the canvasax.plot / ax.bar / ax.scatterdraw the dataset_title, set_xlabel, legendexplain itplt.show()chart appears below output
A Matplotlib chart is built in layers: create a figure and axes, draw the data onto the axes, add labels so readers understand it, then call plt.show(). On this site the finished chart appears as an image under the printed output.

3Matplotlib Basics: explained step by step

Matplotlib turns numbers into pictures. You hand it lists (or NumPy arrays) of values, say what kind of chart you want, add a title and labels, and it draws the figure. Most Python charting tools — including pandas' .plot() — are built on top of it.

The part you use day to day is the pyplot module, imported as plt:

import matplotlib.pyplot as plt

Figure and axes

A chart has two layers. The figure (fig) is the whole image, like a sheet of paper. An axes (ax) is one chart drawn on that sheet, with its own x-axis, y-axis, title and data. plt.subplots() creates both in one call; after that you call methods on ax to draw.

Python
import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
steps = [4200, 6800, 5100, 9000, 7600]

fig, ax = plt.subplots()
ax.plot(days, steps)
ax.set_title("Steps this week")
ax.set_xlabel("Day")
ax.set_ylabel("Steps")
plt.show()

You will also meet shortcut code such as plt.plot(...) and plt.title(...), which draws on whichever axes is "current". It is handy for quick sketches, but calling methods on ax stays clear once a figure holds more than one chart.

Pick the chart that fits the question

  • Line (ax.plot) — how a value changes across something ordered, usually time.
  • Bar (ax.bar) — compare amounts between categories.
  • Scatter (ax.scatter) — check whether two measurements move together.

Labels and legends

A chart without labels makes the reader guess. Give every chart a title and label both axes with set_title, set_xlabel and set_ylabel. When you draw more than one data series, pass label="..." to each one and call ax.legend() to show the key.

Several charts in one figure

plt.subplots(1, 2) makes one row of two axes and returns them as an array, so you draw on axes[0] and axes[1] separately. fig.tight_layout() spaces them out so labels do not overlap.

Where the chart appears

plt.show() displays the figure. On this site the chart becomes an image below the text output, while anything you print() still appears as normal text. In a script on your own computer, plt.show() opens a window instead, and fig.savefig("chart.png") saves the chart as an image file.

4Matplotlib Basics: syntax

import matplotlib.pyplot as plt

fig, ax = plt.subplots()           # one figure, one chart
ax.plot(x, y, label="name")        # line chart
ax.bar(categories, values)         # bar chart
ax.scatter(x, y)                   # scatter plot
ax.set_title("Title")
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.legend()                        # key for labelled series
plt.show()

fig, axes = plt.subplots(1, 2)     # 1 row, 2 charts: axes[0], axes[1]

5Matplotlib Basics: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
coffee = [120, 135, 150, 160, 155, 170]
tea = [80, 85, 70, 95, 100, 110]

fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(months, coffee, marker="o", label="Coffee")
ax.plot(months, tea, marker="s", label="Tea")
ax.set_title("Cups sold per month")
ax.set_xlabel("Month")
ax.set_ylabel("Cups")
ax.legend()

print("Coffee total:", sum(coffee), "| Tea total:", sum(tea))
print("Best coffee month:", months[coffee.index(max(coffee))])
print("Lines on the chart:", len(ax.lines))
plt.show()
Expected outputCoffee total: 890 | Tea total: 540
Best coffee month: Jun
Lines on the chart: 2

7Matplotlib Basics: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1Import the pyplot module under its usual short name plt.
  2. Line 3-5The data: six month names for the x-axis and two lists of the same length for the y-values.
  3. Line 7plt.subplots() creates the figure and one axes. figsize is (width, height) in inches.
  4. Line 8-9Each ax.plot() call draws one line. marker puts a symbol on every data point and label names the line for the legend.
  5. Line 10-12A title and axis labels tell the reader what they are looking at.
  6. Line 13ax.legend() builds the key from the label of each line.
  7. Line 15-16Ordinary print() calls still work: the totals and the best month appear as text output.
  8. Line 17ax.lines holds the line objects drawn on this axes — two of them. Charts are Python objects you can inspect.
  9. Line 18plt.show() renders the figure. Here it appears as an image under the text output.

8Matplotlib Basics: common mistakes

x and y lists of different lengths

✗ Wrong

import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed"]
sales = [12, 19]
fig, ax = plt.subplots()
ax.plot(days, sales)
plt.show()
ValueError: x and y must have same first dimension, but have shapes (3,) and (2,)

✓ Right

import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed"]
sales = [12, 19, 15]
fig, ax = plt.subplots()
ax.plot(days, sales)
plt.show()

Every x value needs exactly one y value. Compare len(days) and len(sales) — here one sales figure is missing.

Using plt-style names on an axes

✗ Wrong

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 3])
ax.xlabel("Day")
plt.show()
AttributeError: 'Axes' object has no attribute 'xlabel'

✓ Right

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 3])
ax.set_xlabel("Day")
plt.show()

plt.xlabel() belongs to the shortcut style. On an axes the methods start with set_: ax.set_xlabel(), ax.set_ylabel() and ax.set_title().

Treating several subplots as one chart

✗ Wrong

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2)
ax.plot([1, 2, 3], [3, 1, 2])
plt.show()
AttributeError: 'numpy.ndarray' object has no attribute 'plot'

✓ Right

import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3], [3, 1, 2])
axes[1].bar(["a", "b"], [4, 2])
plt.show()

When you ask for more than one chart, plt.subplots() returns an array of axes. Pick each chart by index, such as axes[0] and axes[1].

9Matplotlib Basics: exercises

Write your answer, then press Check. The checks run in your browser.

1. Draw a labelled bar chart

Write code Easy

Using languages and votes:

  1. create the figure and axes with fig, ax = plt.subplots(),
  2. draw a bar chart with ax.bar(),
  3. set the title to Favourite languages and the y-axis label to Votes,
  4. call plt.show().

The checks inspect your ax variable, so keep that name.

Your code
import matplotlib.pyplot as plt

languages = ["Python", "Rust", "Go", "Java"]
votes = [31, 12, 9, 17]

# create fig, ax and draw the bar chart

2. Predict what is on each axes

Predict the output Medium

Read the code and type exactly what it prints (ignore the image). ax.lines lists the lines drawn on an axes and ax.patches lists shapes such as bars.

Read this code
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3)
print(len(axes))
axes[0].plot([1, 2, 3], [4, 5, 6], label="up")
axes[0].plot([1, 2, 3], [6, 5, 4], label="down")
axes[2].bar(["x", "y"], [3, 7])
print(len(axes[0].lines), len(axes[1].lines))
print(len(axes[2].patches))
plt.show()

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why doesn't my chart appear when I run the script on my computer?

Add plt.show() after building the chart. In a normal script it opens a window and waits until you close it; without it the program ends before anything is shown. Jupyter notebooks display charts automatically, and fig.savefig("chart.png") writes the chart to a file instead.

What is the difference between plt.plot() and ax.plot()?

plt.plot() draws on the current axes that pyplot keeps track of for you — quick for one chart. ax.plot() draws on the exact axes you name, which is clearer and safer when a figure contains several charts. Both produce the same kind of line.

How do I save a chart as an image file?

Call fig.savefig("chart.png", dpi=150, bbox_inches="tight") before plt.show(). The extension picks the format (.png, .svg, .pdf). In this browser the file goes into the page's temporary file system.

Further reading

10Next lesson

Up nextMatplotlib Chart TypesEach Matplotlib chart type answers a different question, so you choose the chart from the question you are asking: a hi…

Related:
NumPy BasicsPandas Basicspandas groupby and Pivot TablesMatplotlib Chart Types

← pandas Merge, Join and Concat · All Data Analysis lessons · Practise in the IDE