%pylab inline
import numpy as np
import matplotlib.pyplot as plt
Populating the interactive namespace from numpy and matplotlib
Next, let's setup a simple linear space and plot three powers of x on a single plot with a legend and gridines.
x = np.linspace(-5, 5, 100)
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_title('Powers of x', fontdict={'size':22})
ax.plot(x,x,label='$x$')
ax.plot(x,x**2,'rs',label = '$x^2$')
ax.plot(x,x**3,'g^',label = '$x^3$')
ax.plot(x,x**4,'bo',label = '$x^4$')
ax.grid(True)
ax.legend(loc='lower right')
plt.axis([-2,2,-10,10])
[-2, 2, -10, 10]
To make the plots a little less busy, let's make two plots and put two powers on on each.
fig, (ax0,ax1) = plt.subplots(nrows=2)
ax0.set_xlabel('x')
ax0.set_ylabel('f(x)')
ax0.set_title('Powers of x', fontdict={'size':22})
ax0.plot(x,x,label='$x$')
ax0.plot(x,x**2,'rs',label = '$x^2$', markevery=5)
ax1.set_xlabel('x')
ax1.set_ylabel('f(x)')
ax1.plot(x,x**3,'g^',label = '$x^3$', markevery=5)
ax1.plot(x,x**4,'bo',label = '$x^4$', markevery=5)
ax0.grid(True)
ax0.legend(loc='lower right')
ax1.grid(True)
ax1.legend(loc='lower right')
plt.subplots_adjust(hspace=0.5)
Finally, let's put each power on its own plot. Key additions here are the addtion of a linestyle (although I didn't use
it all that creatively), an addtional subplots_adjust command with wspace to adjust the spacing between the plots in each row,
and the suptitle command with sizing to make a single "super" title for the whole plot.
fig, ([ax0, ax1], [ax2, ax3]) = plt.subplots(2,2)
plt.suptitle('Powers of x',fontsize=22)
ax0.set_xlabel('x')
ax0.set_ylabel('f(x)')
ax0.plot(x,x,'b+',label='$x$', markevery=10, linestyle="-")
ax1.set_xlabel('x')
ax1.set_ylabel('f(x)')
ax1.plot(x,x**2,'rs',label='$x^2$', markevery=10, linestyle="-")
ax2.set_xlabel('x')
ax2.set_ylabel('f(x)')
ax2.plot(x,x**3,'g^',label='$x^3$', markevery=10, linestyle="-")
ax3.set_xlabel('x')
ax3.set_ylabel('f(x)')
ax3.plot(x,x**4,'bo',label='$x^4$', markevery=10, linestyle="-")
ax0.grid(True)
ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.subplots_adjust(wspace=0.5)