Matplotlib Plotting

The plot() function is Matplotlib's core tool for drawing lines and points from your data.

The plt.plot() function

plt.plot() is the workhorse function for drawing line charts in Matplotlib. In its simplest form you give it two equal-length sequences of numbers: one for the x-axis positions and one for the y-axis positions, and it connects each (x, y) pair with a straight line.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [3, 6, 5, 9, 12]

plt.plot(x, y)
plt.show()

Plotting with a single argument

If you call plt.plot() with only one sequence, Matplotlib assumes those values are the y-coordinates and automatically generates x-coordinates as the integers 0, 1, 2, and so on. This is convenient when you only care about the shape of a sequence rather than specific x positions.

Example

import matplotlib.pyplot as plt

weekly_visits = [120, 135, 98, 150, 170, 160, 190]

plt.plot(weekly_visits)
plt.show()

Plotting NumPy arrays

plt.plot() also accepts NumPy arrays, which is the more common case in real data work because functions such as np.linspace() and np.arange() make it easy to generate evenly spaced coordinates for smooth curves.

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 50)
y = np.cos(x)

plt.plot(x, y)
plt.show()

Drawing multiple lines

Calling plt.plot() more than once before plt.show() draws each new line on the same axes, which is the simplest way to compare two datasets on one chart.

  • Each call to plt.plot() adds one more line to the current axes
  • Matplotlib automatically assigns a different color to each new line
  • Points, instead of lines, can be shown by adding a marker (covered on the Markers page)
  • The line's own appearance is controlled with linestyle and color (covered on the Line page)

Exercise: Matplotlib Plotting

What does the shorthand format string 'o' do in plt.plot(x, y, 'o')?