Line Charts in Matplotlib

  • Post author:
  • Post category:Python

Line Charts in Matplotlib

We start by importing matplotlib and display all visuals inline

In [1]:
import matplotlib.pyplot as plt
%matplotlib inline

We’ll use the ggplot style in this example for aesthetics

In [2]:
plt.style.use('ggplot')

A simple plot of y = cos(x) between $-\pi$ and $\pi$

In [3]:
import math
import numpy as np

X = np.arange(-math.pi, (math.pi + 0.05), 0.05)

cos_x = np.cos(X)

plt.plot(X, cos_x)
plt.show()

Plotting multiple lines

Plotting multiple lines is as simple as calling plt.plot() more than once

In [4]:
x = np.arange(0, 9)
y1 = 2 ** x
y2 = 256 / 2 ** x
y3 = y1 + y2

plt.plot(x, y1, 'g-')
plt.plot(x, y2, 'r-.')
plt.plot(x, y3, 'b:')

plt.show()

Labels

We can provide labels for the x and y axes and for each of our lines

In [5]:
X = np.arange(-math.pi, (math.pi + 0.05), 0.05)

cos_x = np.cos(X)
sin_x = np.sin(X)

plt.plot(X, cos_x, label='cosine x')
plt.plot(X, sin_x, label='sine x')
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("Sin(x) vs Cos(x)")

plt.legend(loc='upper left')

plt.show()