iPython Notebook for this tutorial is available here.

Matplotlib is a plotting Python library. Its pyplot module provides a MATLAB-like interface.

Import Necessary Packages

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Plot Data

x = np.linspace(-np.pi, np.pi, 20)
y = np.sin(x)
z = np.cos(x)
plt.plot(x, y)
plt.show()
plt.plot(x, z)
plt.show()

png

png

# plot data on a single plot
plt.plot(x, y, label="sin(x)")
plt.plot(x, z, label="cos(x)")

# add legend
plt.legend(loc='upper left')
plt.show()

png

# change line style
plt.plot(x, y, linewidth=2.5, linestyle="dashed", marker="o", color="green")

#configure  X axes
plt.xlim(-4,4)
plt.xticks(np.arange(-4,4,1))

#configure  Y axes
plt.ylim(-1.25,1.25)
plt.yticks(np.arange(-1.25,1.25,0.25))

#labels
plt.xlabel("x")
plt.ylabel("y")

#title
plt.title("My plot")

plt.show()

png

Subplot

fig, axs = plt.subplots(1,2)
axs[0].plot(x, y)
axs[0].set_title("sin(x)")
axs[1].plot(x, z)
axs[1].set_title("cos(x)")
plt.show()

png

Scatter Plot

x = np.random.random(100)
y = np.random.random(100)
                 
plt.scatter(x,y)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Scatter Plot")
plt.show()

png

Barplot

x = np.array(np.arange(1,11))
y = np.random.random_integers(50,size =(10,1))
plt.bar(x,y)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Bar Plot")
plt.show()

png