Matplotlib API中有三层
- matplotlib.backend_bases.FigureCanvas:绘制区域
- matplotlib.backend_bases.Renderer:控制如何在FigureCanvas上绘制
- matplotlib.artist.Artist:控制render如何进行绘制
开发者95%的时间都是在使用Artist。Artist有两种类型:
- primitives(基元):包括Line2D、Text、Rectangle、AxesImage等等
- containers(容器):放置原语的容器,包括Axis、Axes、Figure
标准的用法是创建一个Figure实例F,通过F创建一个或多个Axes实例A,通过A的辅助方法创建基元。
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1) # two rows, one column, first plot
Axes是matplotlib中的最常使用的类,它的很多辅助方法(eg:plot、text、hist、imshow)能够创建基元(分别对应Line2D、Text、Rectangle、AxesImage)。这些辅助方法会自动利用传入的数据创建基元,并将其添加到容器中去,并且在需要的时候绘制出来。如果想手动控制Axes在Figure中的位置,可以通过调用Figure的add_axes方法,该方法传入数组[left, bottom, width, height],其中里面的数字是相对figure的0-1之间的坐标数据
fig2 = plt.figure()
ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3])
当我们调用Axes的plot方法是,实际上就是在Axes中添加了一个Line2D实例
import numpy as np
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax.plot(t, s, color='blue', lw=2)
通过ax.lines方法可以看到,ax中的lines与ax.plot返回的实际上是同一个Line2D实例
如果继续调用ax.plot方法,创建的Line2D对象将继续被添加到ax.lines列表中 ,也可以调用remove方法删掉该实例
line = ax.lines[0]
line.remove()
Axes中也有能设置x轴、y轴刻度、刻度标签和轴标签的方法,每个Axes实例中都包Xies和Yies的实例
xtext = ax.set_xlabel('my xdata') # returns a Text instance
ytext = ax.set_ylabel('my ydata')
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('volts')
ax1.set_title('a sine wave')t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color='blue', lw=2)# Fixing random state for reproducibility
np.random.seed(19680801)ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,facecolor='yellow', edgecolor='yellow')
ax2.set_xlabel('time (s)')plt.show()
Artist对象都包含以下属性
Property | Description |
---|---|
alpha | The transparency - a scalar from 0-1 |
animated | A boolean that is used to facilitate animated drawing |
axes | The Axes that the Artist lives in, possibly None |
clip_box | The bounding box that clips the Artist |
clip_on | Whether clipping is enabled |
clip_path | The path the artist is clipped to |
contains | A picking function to test whether the artist contains the pick point |
figure | The figure instance the artist lives in, possibly None |
label | A text label (e.g., for auto-labeling) |
picker | A python object that controls object picking |
transform | The transformation |
visible | A boolean whether the artist should be drawn |
zorder | A number which determines the drawing order |
rasterized | Boolean; Turns vectors into raster graphics (for compression & EPS transparency) |