Although most of the figure and plot using Matplotlib is about matplotlib.pyplot module, this is not the only way to make use of the Matplotlib plotting power.
There are three ways to use Matplotlib:
• pyplot: The module used so far in this book
• pylab: A module to merge Matplotlib and NumPy together in an environment closer to MATLAT
• Object-oriented way: The Pythonic way to interface with Matplotlib.
Subplot()
fig = plt.figure() # This function returns a Figure, where we can add one or more Axes instances.
ax = fig.add_subplot(111) # This function returns an Axes instance, where we can plot (as done so far), and this is also the reason why we call the variable referring to that instance ax (from Axes). This is a common way to add an Axes to a Figure, but add_subplot() does a bit more: it adds a subplot.
fig.add_subplot(numrows, numcols, fignum)
fig = plt.figure()
ax1 = fig.add_subplot(211) # 2,1,1
ax1.plot([1, 2, 3], [1, 2, 3])
ax2 = fig.add_subplot(212)
ax2.plot([1, 2, 3], [3, 2, 1])
Additional Y(or X) axes
There are situations where we want to plot two sets of data on the same image. In particular, this is the case when for the same X variable, we have two datasets (consider the situation where we take two measurements at the same time, and we want to plot them together to spot some relationships).
The twinx() function does the trick: it creates a second set of axes, putting the new ax2 axes at the exact same position of ax1, ready to be used for plotting.
x = np.arange(0, np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1)
ax1.set_ylabel('Y values for exp(-x)')
ax2 = ax1.twinx()
ax2.plot(x, y2, 'r')
ax2.set_xlim([0, np.e])
ax2.set_ylabel('Y values for ln(x)')
ax1.set_xlabel('Same X for both exp(-x) and ln(x)')
import matplotlib as mpl
mpl.rcParams['font.size'] = 10
import matplotlib.pyplot as plt
....
这里需要注意的是:利用上述方法避免多张图片的坐标,标尺重叠。
Matplotlib makes it very easy to share an axis (for example, the X one) on different Axes instances, for example, pan and zoom actions on one graph are automatically replayed to all the others.
ax2 = fig.add_subplot(312, sharex=ax1)
Plotting dates
import datetime as dt
print dt.datetime.today()
Note how we had to convert our date values using the date2num() function. This is because Matplotlib represents dates as float values corresponding to the number of days since 0001-01-01 UTC.
网友评论