Matplotlib Tutorials


Part 1 : Basic Functions

Before you start this tutorial you need to know some useful functions in numpy.
The following code illustrates what you may need for matplotlib library.

In [3]:
import numpy as np

x = np.arange(4)
print(x)

x = np.arange(start=0, stop=10, step=2)
print(x)

x = np.linspace(start=2.0, stop=3.0, num=5)
print(x)

x = np.linspace(0, 1, 3)
y = np.linspace(0, 1, 5)
xv, yv = np.meshgrid(x, y)
zv = xv + yv
print(xv)
print(yv)
print(zv)
[0 1 2 3]
[0 2 4 6 8]
[2.   2.25 2.5  2.75 3.  ]
[[0.  0.5 1. ]
 [0.  0.5 1. ]
 [0.  0.5 1. ]
 [0.  0.5 1. ]
 [0.  0.5 1. ]]
[[0.   0.   0.  ]
 [0.25 0.25 0.25]
 [0.5  0.5  0.5 ]
 [0.75 0.75 0.75]
 [1.   1.   1.  ]]
[[0.   0.5  1.  ]
 [0.25 0.75 1.25]
 [0.5  1.   1.5 ]
 [0.75 1.25 1.75]
 [1.   1.5  2.  ]]

Part 2 : Simple Plots

In [4]:
# How to draw a Curve in Matplotlib
from matplotlib import pyplot as plt
import numpy as np

x = np.arange(0, np.pi*2, 0.05)
#print(x)
y = np.sin(x)

plt.title("sine function")
plt.xlabel("angle")
plt.ylabel("sine")
plt.plot(x,y)
plt.show()
In [6]:
import numpy as np
import pylab as plt

x = np.linspace(-3, 3, 30)
plt.plot(x,  np.sin(x))
plt.plot(x,  np.cos(x), 'r.')
plt.plot(x, -np.sin(x), 'g--')

plt.show()
In [8]:
import matplotlib.pyplot as plt

y  = [ 1, 4,  9, 16, 25, 36, 49, 64]
x1 = [ 1,16, 30, 42, 55, 68, 77, 88]
x2 = [ 1, 6, 12, 18, 28, 40, 52, 65]

fig = plt.figure()

ax = fig.add_axes([0,0,1,1])
l1 = ax.plot(x1,y,'ys-')
l2 = ax.plot(x2,y,'go--')

ax.legend(labels=('tv','Smartphone'), loc='lower right')
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')

plt.show()
In [9]:
import matplotlib.pyplot as plt

x = np.arange(1,10)
y = x ** 2

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.grid(color='b', ls = '-.', lw = 0.25)
ax.spines['bottom'].set_color('green')
ax.spines['left'  ].set_color('red' )
ax.spines['left'  ].set_linewidth(2)
ax.spines['right' ].set_color(None)
ax.spines['top'   ].set_color(None)
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.plot(x,y)

plt.show()
In [10]:
import matplotlib.pyplot as plt

x = np.arange(1,10)
y = np.exp(x)

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.grid(color='b', ls = '-.', lw = 0.25)
ax.spines['bottom'].set_color('green')
ax.spines['left'  ].set_color('red' )
ax.spines['left'  ].set_linewidth(2)
ax.spines['right' ].set_color(None)
ax.spines['top'   ].set_color(None)
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_xlim(0,8)
ax.set_ylim(0,1000)
ax.plot(x,y)

plt.show()
In [11]:
import matplotlib.pyplot as plt

x_ticks = ['A','B','C','D','E','F','G','H']
y_ticks = ['Bao','Jiarong','Sahli','Simo','Xiarong']
x = np.arange(1,10)
y = np.exp(x)

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.grid(color='b', ls = '-.', lw = 0.25)
ax.spines['bottom'].set_color('green')
ax.spines['left'  ].set_color('red' )
ax.spines['left'  ].set_linewidth(2)
ax.spines['right' ].set_color(None)
ax.spines['top'   ].set_color(None)
ax.set_xlabel("x axis")
ax.set_ylabel("y axis")
ax.set_xlim(0,8)
ax.set_ylim(0,1000)
ax.set_title('Exponential')
ax.set_xticks(x)
ax.set_xticklabels(x_ticks)
ax.set_yticklabels(y_ticks)

ax.plot(x,y)
Out[11]:
[<matplotlib.lines.Line2D at 0x118bc9ca0>]

Exercise 1:

Try different mathematical functions.
for example: cos(x), tan(x), exp(x), log(x)

In [9]:
from matplotlib import pyplot as plt
import numpy as np

x = np.arange(0.1, np.pi*2, 0.05)
y = np.log(x)

plt.title("sine function")
plt.xlabel("angle")
plt.ylabel("sine")
plt.plot(x,y)
plt.show()

Prat 3 : Subplots

In [4]:
import matplotlib.pyplot as plt
import numpy as np

fig,a =  plt.subplots(2,2)
x = np.arange(0, np.pi*2, 0.05)
a[0][0].plot(x,np.sin(x))
a[0][0].set_title('sin')
a[0][1].plot(x,np.cos(x))
a[0][1].set_title('cos')
a[1][0].plot(x,np.exp(x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.sqrt(x))
a[1][1].set_title('sqrt')
plt.show()
In [21]:
import matplotlib.pyplot as plt
import numpy as np

a1 = plt.subplot2grid((3,3),(0,0),colspan=2)
a2 = plt.subplot2grid((3,3),(0,2),rowspan=3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan=2,colspan=2)
x  = np.arange(0, np.pi*2, 0.05)

a1.plot(x, np.sin(x))
a1.set_title('sin')
a3.plot(x, np.cos(x))
a3.set_title('cos')
a2.plot(x, np.exp(x))
a2.set_title('exp')
plt.show()
In [6]:
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(1,3, figsize = (12,4))
x = np.arange(1,11)

axes[0].plot(x, x**3, 'g',lw=2)
axes[0].grid(True)
axes[0].set_title('default grid')

axes[1].plot(x, np.exp(x), 'r')
axes[1].grid(color='b', ls = '-.', lw = 0.25)
axes[1].set_title('custom grid')

axes[2].plot(x,x)
axes[2].set_title('no grid')

fig.tight_layout()
plt.show()
In [7]:
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.arange(1,5,0.1)

axes[0].plot(x, np.exp(x))
axes[0].plot(x, x ** 2)
axes[0].set_title("Normal scale")
axes[1].set_yscale("linear")
axes[0].set_xlabel("x axis")
axes[0].set_ylabel("y axis")
axes[0].xaxis.labelpad = 10

axes[1].plot(x, np.exp(x))
axes[1].plot(x, x ** 2)
axes[1].set_yscale("log")   #others: logit, symlog
axes[1].set_title("Logarithmic scale (y)")
axes[1].set_xlabel("x axis")
axes[1].set_ylabel("y axis")

plt.show()
In [8]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1,11)

fig = plt.figure()
a1  = fig.add_axes([0.1,0.1,0.85,0.85])
a1.grid(color='b', ls = '-.', lw = 0.25)
a2 = a1.twinx()

a1.plot(x, np.exp(x))
a1.set_ylabel('exp')

a2.plot(x, np.log(x),'ro-')
a2.set_ylabel('log')

fig.legend(labels = ('exp','log'),loc='upper left')
plt.show()

Exercise 2 :

Plot in 2x2 grid of the following functions.
For example: cos(x), sin(x), exp(x), log(x)

In [13]:
import matplotlib.pyplot as plt
import numpy as np

fig,a =  plt.subplots(2,2)
x = np.arange(0.1, np.pi*2, 0.05)
a[0][0].plot(x,np.sin(x))
a[0][0].set_title('sin')
a[0][1].plot(x,np.cos(x))
a[0][1].set_title('cos')
a[1][0].plot(x,np.exp(x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log(x))
a[1][1].set_title('log')
plt.show()

Part 4 : Graphs

Bar Plot 1/3

In [9]:
import matplotlib.pyplot as plt

fig = plt.figure()
ax  = fig.add_axes([0.1,0.1,0.85,0.85])
ax.set_xlabel("Programming Languages")
ax.set_ylabel("Number of Students")
langs   = ['C', 'C++', 'Java', 'Python', 'PHP']
students= [23,17,35,29,12]
ax.bar(langs,students)
plt.show()

Bar Plot 2/3

In [10]:
import numpy as np
import matplotlib.pyplot as plt

data = [[30, 25, 50, 20],
        [40, 23, 51, 17],
        [35, 22, 45, 19]]
X  = np.arange(4)

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)
plt.show()

Bar Plot 3/3

In [22]:
import numpy as np
import matplotlib.pyplot as plt

men_scores   = (20, 35, 30, 35, 27)
women_scores = (25, 32, 34, 20, 25)
ind = np.arange(5) # the x locations for the groups

fig = plt.figure()
ax  = fig.add_axes([0.1,0.1,0.85,0.85])
ax.bar(ind, men_scores  , width = 0.35, color = 'r')
ax.bar(ind, women_scores, width = 0.35, bottom= men_scores, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
# ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels = ['Men', 'Women'])
plt.show()

Part 5 : Pie Chart

In [5]:
from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax  = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs    = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs, autopct = '%1.2f%%')
plt.show()

Part 6 : Scatter Plot

In [14]:
import matplotlib.pyplot as plt

girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80,  34]
boys_grades  = [30, 29, 49, 48, 100, 48, 38,  45, 20,  30]
grades_range = [10, 20, 30, 40,  50, 60, 70,  80, 90, 100]

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.scatter(grades_range, girls_grades, color='r')
ax.scatter(grades_range, boys_grades , color='b')
ax.set_xlabel('Grades Range')
ax.set_ylabel('Grades Scored')
ax.set_title('scatter plot')
plt.show()

Exercise 3:

Draw a graph using pandas and matplotlib for the file shown on the right.

In [15]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df= pd.read_csv("datas/temperature.csv",sep=';',header=0)
df= df.sort_values(by='Year')
A = np.array([])
B = np.array([])
A = np.append(A,df['Year'].values)
B = np.append(B,df['Anomaly'].values)

fig= plt.figure()
ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.grid(color='gray', lw = 0.25)
ax.set_ylim(0,1)
ax.plot(A,B)

ax.set_xlabel('Year')
ax.set_ylabel('Anomaly')

plt.show()

Exercise 4:

Draw a graph using pandas and matplotlib for the file shown on the right.

In [23]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.read_csv("datas/temperature.csv",sep=';',header=0)
df = df.sort_values(by='Year')
A  = np.array([])
B  = np.array([])
A  = np.append(A,df['Year'].values)
B  = np.append(B,df['Anomaly'].values)

fig = plt.figure()
ax  = fig.add_axes([0.1,0.1,0.85,0.85])
ax.set_xlabel("Year")
ax.set_ylabel("Anomaly")
ax.grid(axis="y",color='gray', lw = 0.25)
ax.bar(A,B)
plt.show()

Exercise 5:

Draw a graph using pandas and matplotlib for the file shown on the right.

In [24]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df= pd.read_csv("datas/energy.csv",sep=':',header=0)
A = np.array([])
B = np.array([])
C = np.array([])

A = np.append(A,df['Resource'].values)
B = np.append(B,df['Percentages'].values)
C = np.append(C,df['Rate'].values)

fig = plt.figure()
ax  = fig.add_axes([0.1,0.1,0.85,0.85])
ax.axis('equal')  # 饼图长宽相等
ax.pie(B, labels = A, autopct = '%1.2f%%',startangle=0,counterclock=False)
plt.show()

Part 7 : 3D Plot

In [15]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

fig= plt.figure()
ax = plt.axes(projection='3d')
ax.set_title('3D line plot')

z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)

ax.plot(x, y, z, 'blue')
# ax.plot3D(x, y, z, 'red')
plt.show()

Part 8 : Scatter

In [16]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

fig= plt.figure()
ax = plt.axes(projection='3d')
ax.set_title('3d Scatter plot')

z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
c = x + y

ax.scatter(x, y, z, s=20, c=c)
plt.show()
In [25]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax  = plt.axes(projection='3d')
ax.set_title('3D contour')
ax.scatter(X, Y, Z, s = 10, c = '#5E9CFF')
plt.show()

Part 9 : Wireframe Plot

In [26]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax  = plt.axes(projection='3d')
ax.set_title('3D contour')
ax.plot_wireframe(X, Y, Z)
plt.show()

Part 10 : Surface Plot

In [27]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax  = plt.axes(projection='3d')
ax.set_title('3D contour')
ax.plot_surface(X, Y, Z)
plt.show()

Part 11 : Contour3D

In [28]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax  = plt.axes(projection='3d')
ax.set_title('3D contour')
ax.contour3D(X, Y, Z, 100)
plt.show()

Exercise 6:

Implement all the following mathematical functions.

In [29]:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

def ackley(x, y):
   return -20*np.exp(-0.2*np.sqrt(0.5*(x**2+y**2)))- \
           np.exp(0.5*(np.cos(2*np.pi*x)+np.cos(2*np.pi*y)))+np.e+20

x = np.linspace(-6, 6, 300)
y = np.linspace(-6, 6, 300)

X, Y = np.meshgrid(x, y)
Z = ackley(X, Y)

fig = plt.figure()
ax  = plt.axes(projection='3d')
ax.set_title('3D contour')
ax.plot_surface(X, Y, Z,cmap = plt.get_cmap('rainbow'))
plt.show()

Part 12 : Text

In [22]:
import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0.1,0.1,0.85,0.85])
ax.axis([0, 10, 0, 10])
ax.grid(color='b', ls = '-.', lw = 0.25)
ax.set_title('Playing with texts')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')

ax.plot([1], [2], 'ro')
ax.text(1,2,'Hi, Bao Jiarong!',color='blue', fontsize=15)

plt.show()

Part 13 : Images

Read, save and show the image

In [38]:
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Read, Save and Show image
img = mpimg.imread("img/dog.png")
# ... Do anything you like with the image
# ...
mpimg.imsave("img/dog2.png",img)
plt.imshow(img)
plt.show()

Part 14 : More Tutorials

link1

link2