matplotlib usage examples
As presented in cm3015 Topic 01: Introduction, lab 4
Plot an exponential
#generate 200 uniformly sampled points in the range -2 to 2
x = np.linspace(-2, 2, 200)
#estimate the product of a polynomial with an exponential function
y = (x**5 + 2*x**4 + 4*x**3 + 2*x**2 + x + 5)*np.exp(-x**2)
plt.plot(x, y)#matplotlib plot
plt.grid(True)
Plot a sin wave
x = np.linspace(-np.pi, np.pi, 200)
y = np.sin(x)
plt.plot(x,y)
plt.grid(True)
Plot a natural exponential or logarthmic function
x2 = np.linspace(0, 10.0, 200)
y2 = np.exp(-x2)
plt.plot(x2, y2)
plt.grid(True)
y3 = np.log(x2)
plt.plot(x2, y3)
plt.grid(True)
Load a dataset, describe and plot it
from sklearn import datasets
iris = datasets.load_iris()
# view a description of the dataset
print(iris.DESCR)
#This populates info regarding the dataset. Amongst others, we can see that the 'features' used are sepal length and width and petal length and width
#Lets plot sepal length against sepal width, using the target labels (which flower)
X=iris.data
Y=iris.target
#first two features are sepal length and sepal width
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
Plot in 3D
#here's also how to plot in 3d:
from mpl_toolkits.mplot3d import Axes3D #
#create a new figure
fig = plt.figure(figsize=(5,5))
#this creates a 1x1 grid (just one figure), and now we are plotting subfigure 1 (this is what 111 means)
ax = fig.add_subplot(111, projection='3d')
#plot first three features in a 3d Plot. Using : means that we take all elements in the correspond array dimension
ax.scatter(X[:, 0], X[:, 1], X[:, 2],c=Y)
Create multiple subplots
#here's how to create a figure with multiple subplots
#here's also how to plot in 3d:
fig = plt.figure(figsize=(10,4))
#this creates a 1x2 grid (two figures), and now we are plotting subfigure 1 (this is what 121 means)
ax = fig.add_subplot(121)
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
#note that in the first figure, we did not use commas for 121, and in the second, we used 1,2,2. Both these methods work
ax = fig.add_subplot(1,2,2, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2],c=Y)
ax.set_xlabel('Sepal length')
ax.set_ylabel('Sepal width')
ax.set_zlabel('Petal length')