Google - Search - matplotlib tutorial
# 0) import modules for graphing
# (numpy = for array/vector computing
# (matplotlib.pyplot = for ploting in Python
import numpy as np
import matplotlib.pyplot as plt
# (1) Define X-values
X = np.linspace(0,10,11, endpoint=True)
# (2) Plot several functions in one graph + use simple formatting
# ('b-' = Blue+line, 'rs' = Red+square, 'g--' = Green+dashedline
# ('k:' = blacK+dotted line, 'mo' = Magenta+circle
plt.plot(X,X, 'b-' , label='f(x)=x')
plt.plot(X,X, 'rs')
plt.plot(X,2*X, 'g--', label='f(x)=2x')
plt.plot(X,3*X, 'k:' , label='f(x)=3x')
plt.plot(X,4*X, 'mo' , label='f(x)=4x')
plt.grid()
plt.legend()
plt.show()
# 1) Define X
X = [1,2,3,4,5,6]
# 2) Define Y
Y = [2,10,18,36,54,86]
# 3) Define labels
X_labels = ['He','Ne','Ar','Kr','Xe','Rn']
# 4) Plot the results
plt.bar(X,Y, width=0.6, color='red', zorder=10)
plt.xticks(X,X_labels)
plt.title('Atomic number of noble gases')
plt.ylabel('Atomic number')
plt.grid(axis='y')
plt.show()
# Function of two variables
def f(x,y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
# X,Y variables
X = np.linspace(0,3,301, endpoint=True)
Y = np.linspace(0,3,301, endpoint=True)
# Prepare X and Y for 3D-plotting
# => 1D-arrays must be converted to 2D-meshes so that f(X,Y) was 2D-mesh
# => special numpy function, take it as a template OR see www for more info
Xm,Ym = np.meshgrid(X,Y)
# Prepare Z data = f(X,Y) = f(Xm,Ym)
Z = f(Xm,Ym)
# (1a) Contour plot, black
plt.gca().set_aspect('equal')
plt.contour(X,Y,Z, 20, colors='black')
plt.show()
# (1b) Contour plot, colors
plt.gca().set_aspect('equal')
plt.contour(X,Y,Z, 20, cmap='coolwarm')
plt.show()
# (2) Density plot, colors, with colorbar
# (colorbar maps the colors to numeric values
plt.gca().set_aspect('equal')
plt.contourf(X,Y,Z, 20, cmap='coolwarm')
plt.colorbar()
plt.show()
# (3) Plot array as image
# (in imshow we can specify cmap as well
# (here we leave default; frequent colormap in microscopy: cmap='gray'
plt.gca().set_aspect('equal')
plt.imshow(Z)
plt.colorbar()
plt.show()
# (1) Import modules for 3D-plotting
# ...standard imports (done above, but repeated for completness)
import numpy as np
import matplotlib.pyplot as plt
# ...special matplotlib toolkit for 3D-plotting
from mpl_toolkits.mplot3d import Axes3D
# (2) Plot the result = f(x,y)
# (take this as a template OR see www for more info
# a) create basic figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# b) plot the prepared data
ax.plot_surface(Xm,Ym,Z, cmap='coolwarm', linewidth=0, antialiased=False)
plt.show()