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.
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)
# 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()
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()
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()
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()
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()
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)
Try different mathematical functions.
for example: cos(x), tan(x), exp(x), log(x)
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()
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()
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()
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()
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()
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()
Plot in 2x2 grid of the following functions.
For example: cos(x), sin(x), exp(x), log(x)
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()
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()
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()
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()
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()
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()
Draw a graph using pandas and matplotlib for the file shown on the right.
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()
Draw a graph using pandas and matplotlib for the file shown on the right.
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()
Draw a graph using pandas and matplotlib for the file shown on the right.
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()
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()
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()
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()
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()
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()
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()
Implement all the following mathematical functions.
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()
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()
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()