Often we want to create two or more graphs and place them next to one another, generally because they are related to each other in some way. For example see the graph shown below:
In the top graph, are plotted. The two curves cross each other at the points where In the bottom are plotted. These two curves cross each other at the points where See the code below which produces the above shown graphs:import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0.01, 8., 0.04)
y = np.sqrt((8. / theta) ** 2 - 1.)
ytan = np.tan(theta)
ytan = np.ma.masked_where(np.abs(ytan) > 20., ytan)
ycot = 1. / np.tan(theta)
ycot = np.ma.masked_where(np.abs(ycot) > 20., ycot)
plt.figure(figsize=(8.5, 6))
plt.subplot(2, 1, 1)
plt.plot(theta, y, linestyle=':')
plt.plot(theta, ytan)
plt.xlim(0, 8)
plt.ylim(-8, 8)
plt.axhline(color="gray", zorder=-1)
plt.axvline(x=np.pi / 2., color="gray", linestyle='--',
zorder=-1)
plt.axvline(x=3. * np.pi / 2., color="gray", linestyle='--',
zorder=-1)
plt.axvline(x=5. * np.pi / 2., color="gray", linestyle='--',
zorder=-1)
plt.xlabel("theta")
plt.ylabel("tan(theta)")
plt.subplot(2, 1, 2)
plt.plot(theta, -y, linestyle=':')
plt.plot(theta, ycot)
plt.xlim(0, 8)
plt.ylim(-8, 8)
plt.axhline(color="gray", zorder=-1)
plt.axvline(x=np.pi, color="gray", linestyle='--',
zorder=-1)
plt.axvline(x=2. * np.pi, color="gray", linestyle='--',
zorder=-1)
plt.xlabel("theta")
plt.ylabel("cot(theta)")
plt.savefig('figures/subplotDemo.pdf')
plt.show()
The function subplot, called on lines 13 and 28, creates the two subplots in the above figure. subplot has three arguments. The first specifies the number of rows into which the figure space is to be divided : in line 13, it’s 2. The second specifies the number of columns into which the figure space is to be divided; in line 13, it’s 1. The third argument specifies which rectangle will contain the plot specified by the following function calls. Line 13 specifies that the plotting commands that follow will act on the first box. Line 28 specifies that the plotting commands that follow will be act on the second box. As a convenience, the commas separating the three arguments in the subplot routine can be omitted, provided they are all single-digit arguments (less than or equal to 9). For example, lines 13 and 28 can be written as
plt.subplot(211)
.
.
plt.subplot(212)
Finally, we have also labeled the axes and included dashed vertical lines at the values of where tan and cot diverge.
0 comments:
Post a Comment