TExcelTAD
Home › Matplotlib › Matplotlib Pyplot

Matplotlib Pyplot

matplotlib.pyplot is a collection of functions that make Matplotlib work like a simple drawing program: each call changes the current figure a little, by adding a line, a title, a label or a legend. It is the quickest way to get a chart on screen.

python · try it yourself
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
rainfall = [78, 61, 55, 47, 52, 40]

plt.plot(months, rainfall)
plt.title("Monthly rainfall (mm)")
plt.xlabel("Month")
plt.ylabel("Rainfall")
plt.show()

print("Total rainfall:", sum(rainfall), "mm")
Total rainfall: 333 mm

Notice that the x values can be strings. Matplotlib treats them as categories and places them at evenly spaced positions in the order they first appear.

The "current figure" idea

Pyplot keeps track of a current figure and a current Axes (the plotting area inside the figure). Every function such as plt.plot, plt.title or plt.xlim acts on them. If no figure exists yet, the first plotting call creates one.

Function Purpose
plt.figure() Start a new figure and make it current
plt.plot(x, y) Draw lines and/or markers
plt.title(text) Title above the plot
plt.xlabel(text) / plt.ylabel(text) Axis labels
plt.xlim(a, b) / plt.ylim(a, b) Set the visible range of an axis
plt.gcf() / plt.gca() "Get current figure" / "get current Axes"
plt.show() Display all open figures
plt.close() Close the current figure (plt.close("all") closes all)

Several lines on one chart

Calling plt.plot again adds another line to the same Axes. Matplotlib picks a new colour for each line automatically:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4, 50)

plt.plot(x, x)
plt.plot(x, x ** 2)
plt.plot(x, np.sqrt(x))
plt.title("Three curves, one Axes")
plt.show()

ax = plt.gca()
print("Lines on the current Axes:", len(ax.lines))
Lines on the current Axes: 3

plt.gca() returns the current Axes object, and its lines attribute lists every line drawn on it. This is your first peek at the object-oriented API hiding behind pyplot.

Separate figures

To get two independent charts, start a new figure before the second one. figsize sets the size in inches (width, height):

python · try it yourself
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 3))
plt.plot([1, 2, 3], [3, 1, 2])
plt.title("First figure")

plt.figure(figsize=(5, 3))
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("Second figure")

plt.show()
print("Open figures:", plt.get_fignums())
Open figures: [1, 2]

Both figures remain open, so both are drawn under the output. plt.get_fignums() returns the numbers of the open figures.

Setting the axis range

By default the axes fit the data with a small margin. plt.xlim and plt.ylim override that, which is useful when you want a chart to start at zero:

python · try it yourself
import matplotlib.pyplot as plt

scores = [62, 68, 71, 75, 74, 80]

plt.plot(range(1, 7), scores)
plt.ylim(0, 100)
plt.title("Test scores on a 0-100 scale")
plt.show()

low, high = plt.ylim()
print("y axis runs from", low, "to", high)
y axis runs from 0.0 to 100.0

Called with no arguments, plt.ylim() returns the current limits instead of setting them.

Note: If you pass only y (for example plt.plot(scores)), Matplotlib uses 0, 1, 2, … as the x values.

Test yourself

What does plt.gca() return?

  1. The current figure
  2. The current Axes
  3. A list of all figures
  4. The colour cycle

You call plt.plot(a) and then plt.plot(b) without anything in between. What do you get?

  1. Two separate figures
  2. An error
  3. Two lines in the same Axes
  4. Only line b; line a is replaced

What does figsize=(6, 4) mean in plt.figure(figsize=(6, 4))?

  1. 6 by 4 pixels
  2. 6 inches wide and 4 inches tall
  3. 6 rows and 4 columns of subplots
  4. Font size 6, line width 4