前言
这个教程涵盖了一些更复杂的类和函数, 他们可用于特定的自定义和复杂的可视化. 四大容器的基本用法
Artist tutorial
There are three layers to the Matplotlib API.
- the
matplotlib.backend_bases.FigureCanvas
is the area onto which the figure is drawn - the
matplotlib.backend_bases.Renderer
is the object which knows how to draw on theFigureCanvas
- and the
matplotlib.artist.Artist
is the object that knows how to use a renderer to paint onto the canvas
matplotlib API 有三层:
- backend_bases.FigureCanvas : 图表的绘制领域
- backend_bases.Renderer : 知道如何在 FigureCanvas 上如何绘图
- artist.Artist : 知道如何使用 Renderer 在 FigureCanvas 上绘图
FigureCanvas 和 Renderer 需要处理底层的绘图操作,例如使用 wxPython 在界面上绘图,或者使用 PostScript 绘制 PDF。Artist 则处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和 Artist 打交道,而不需要关心底层的绘制细节。
在 matplotlib 中最重要的基类 Artist 类及其派生类,主要分为容器类型和绘图元素类型两类,容器类型包括中 Figure,Axes,Axis,这些类确定一个绘图区域,为元素类型提供显示位置;绘图元素类型包括 Line2D、 Rectangle、 Text、AxesImage 等,这些是包含在容器类型提供的绘图区域中。
有两类 Aritists: primitives 和 containers. primitives (原语) 代表了我们想要在画布上绘制的标准图形对象, 例如: Line2D, Rectangle, Text, AxesImage 等. containers (容器) 是放置他们的地方 包含Axis, Axes, Figure.
当你调用ax.plot 时, Axes实例会创建一个Line2D实例,并将其添加到Axes上.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
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列表只有一个元素, 包含的元素和line, = ax.plot()返回的是一个.
In [101]: ax.lines[0]
Out[101]: <matplotlib.lines.Line2D at 0x19a95710>
In [102]: line
Out[102]: <matplotlib.lines.Line2D at 0x19a95710>
调用remove方法, 移除Line2D
line.remove()
当你调用ax.set_xlabel, 它会将Text实例上的消息传递给XAxis. 每个Axes实例包含一个XAxis和一个YAxis实例
xtext = ax.set_xlabel('my xdata') # returns a Text instance
ytext = ax.set_ylabel('my ydata')
Customizing your objects
figure中的每一个元素都由一个Matplotlib Artist表示, 而且有一个广泛的属性的列表用以配置其外观. figure本身包含一个Rectangle 恰好是figure 的大小. 可以用来设置背景颜色和figure透明度. 同样, 每个Axes边界框都有一个Rectangle实例决定了颜色, 透明度, 和其他Axes属性. 这些实例都存储在成员变量Figure.patch 和 Axes.patch中.(patch这个名字继承自matlab, 也是一个在figure上的2D颜色patch(色块)).
每一个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) |
查看Aritist属性
In [149]: matplotlib.artist.getp(fig.patch)
'''
agg_filter = None
alpha = None
animated = False
antialiased or aa = False
bbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)
capstyle = butt
children = []
clip_box = None
clip_on = True
clip_path = None
contains = None
data_transform = BboxTransformTo( TransformedBbox( Bbox...
edgecolor or ec = (1.0, 1.0, 1.0, 1.0)
extents = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)
facecolor or fc = (1.0, 1.0, 1.0, 1.0)
figure = Figure(640x480)
fill = True
gid = None
hatch = None
height = 1
in_layout = False
joinstyle = miter
label =
linestyle or ls = solid
linewidth or lw = 0.0
patch_transform = CompositeGenericTransform( BboxTransformTo( ...
path = Path(array([[0., 0.], [1., 0.], [1.,...
path_effects = []
picker = None
rasterized = None
sketch_params = None
snap = None
transform = CompositeGenericTransform( CompositeGenericTra...
transformed_clip_path_and_affine = (None, None)
url = None
verts = [[ 0. 0.] [640. 0.] [640. 480.] [ 0. 480....
visible = True
width = 1
window_extent = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)
x = 0
xy = (0, 0)
y = 0
zorder = 1
'''
Object containers
在本节中, 我们将回顾各种容器对象将你想要获取的 Aritst 都存在了哪里.
figure 包含多个 axes
axes 包含两个 axis(二维图)
axis 包含 多个 tick.
Figure container
一级(顶级)container Artist 是 mpl.figure.Figure, 它包含 figure 中的所有东西. figure 的背景是一个存在 Figure.patch 中的 Rectangle. 当你添加 subplots 和 axes 到 figure 中, 他们会被添加到 Figure.axes 中.
In [156]: fig = plt.figure()
In [157]: ax1 = fig.add_subplot(211)
In [158]: ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])
In [159]: ax1
Out[159]: <AxesSubplot:>
In [160]: print(fig.axes)
[<AxesSubplot:>, <matplotlib.axes._axes.Axes object at 0x7f0768702be0>]
因为 figure 保持了当前 axes 的概念以支持 pylab/pyplot 状态机, 所以你不应该直接在 axes 列表里插入或删除, 而是使用 add_subplot() 和 add_axes() 方法插入, 用 Axes.remove() 删除.
你可以自由迭代 axes 或 index 列表以访问你想要自定义的实例.
for ax in fig.axes:
ax.grid(True)
figure 也有他自己的 images, lines, patches, text 属性, 你可以用他们直接添加原语(primitive). 如果这样做, figure 的默认坐标系将会是像素坐标系(单位是像素). 如果你用 figure 级别的方法添加 Artists(例如 用 Figure.text 添加 text), 那么默认坐标系将会是 figure 坐标系(左下角(0, 0), 右上角(1, 1)), 可以更好处理大小和比例.
像素坐标系指的是图形中点的位置是以像素为单位进行计算的坐标系。图形的大小和位置是以像素为单位进行描述的。
figure 坐标系是相对于整个图形窗口的坐标系。在 figure 坐标系中,坐标点的单位是相对于整个 figure 的大小,因此它在不同大小的窗口中的位置是相对固定的。
import matplotlib.lines as lines
fig = plt.figure()
l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)
l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)
fig.lines.extend([l1, l2])
plt.show()
Figure attribute | Description |
---|---|
axes | A list of Axes instances (includes Subplot) |
patch | The Rectangle background |
images | A list of FigureImage patches - useful for raw pixel display |
legends | A list of Figure Legend instances (different from Axes.legends ) |
lines | A list of Figure Line2D instances (rarely used, see Axes.lines ) |
patches | A list of Figure Patch s (rarely used, see Axes.patches ) |
texts | A list Figure Text instances |
Axes container
该容器包含了大量 Artists,
像 Figure, 它包含了一个 Patch, 一个 Rectangle 为笛卡尔坐标系使用, 一个 Circle 为极坐标系使用. 这个 Patch 决定了形状, 背景和绘图区域的边界.
来自 chatgpt:
在编程中,“helper method” 指的是一个在执行某个任务时协助完成的辅助方法。辅助方法的主要作用是使代码更具可读性、可维护性和可复用性,因为将任务分解为较小的方法可以使代码更加模块化和简洁。
通常,helper method 不是在功能上与主方法平行的,而是去做一些简单、重复或较少发生变化的具体工作,以减轻主方法的压力。helper method 可以是公共的或私有的,公共的辅助方法通常是可复用的,而私有的辅助方法只是在主方法内使用。
helper method 可以使用这样的方式来定义它们的作用范围:如果它们是在类中定义的,则通常被称为实例方法或静态方法,如果它们是在模块或库中定义的,则通常被称为辅助函数。
helper method 是一个常用的编程技巧,可以在编写模块、类或方法时使用。通过设计和使用 helper method,编写更复杂和可读性更强的代码变得更加容易,同时可以提高代码质量,减少代码的重复部分。
fig = plt.figure()
ax = fig.add_subplot()
rect = ax.patch # a Rectangle instance
rect.set_facecolor('green')
x, y = np.random.rand(2, 100)
line, = ax.plot(x, y, '-', color='blue', linewidth=2)
plt.show()
plot 返回 line 列表因为你可以传入多个 x, y 对.
我们将列表的第一个元素解包出来传入 line 变量, 这条 line 被添加到了 Axes.lines 列表里.
不应该直接将对象添加到 lines 和 patches 列表里, 因为 Axes 需要在创建和添加对象时做点事.
- 它会设置 Artist 的 figure 和 axes 属性.
- 它会设置默认 Axes transformation
- 它会查看 Artist 中的数据以更新控制自动缩放的数据结构, 以便视图限制可以调整以包含绘制的数据.
尽管如此, 你可以创建对象并直接将他们添加到 Axes 中, 用帮手方法(helper method) 例如 add_line 和 add_patch. 就是比较麻烦.
常见 helper method 以及创建的 Artist 和所属 Container
Axes helper method | Artist | Container |
---|---|---|
annotate - text annotations | Annotation | ax.texts |
bar - bar charts | Rectangle | ax.patches |
errorbar - error bar plots | Line2D and Rectangle | ax.lines and ax.patches |
fill - shared area | Polygon | ax.patches |
hist - histograms | Rectangle | ax.patches |
imshow - image data | AxesImage | ax.images |
legend - Axes legends | Legend | ax.legends |
plot - xy plots | Line2D | ax.lines |
scatter - scatter charts | PolyCollection | ax.collections |
text - text | Text | ax.texts |
Axes 容器还包含两个重要的 Artist 容器: XAxis 和 YAxis, 他们处理刻度和标签. 这些被存放在实例对象 xaxis 和 yaxis.
注意许多 helper method 会将调用转发给 Axis 实例, 所以你通常不需要直接和他们工作, 除非你愿意.
例如
for label in ax.get_xticklabels():
label.set_color('orange')
下面是 Axes 包含的 Artist 的总结.
Axes attribute | Description |
---|---|
artists | A list of Artist instances |
patch | Rectangle instance for Axes background |
collections | A list of Collection instances |
images | A list of AxesImage |
legends | A list of Legend instances |
lines | A list of Line2D instances |
patches | A list of Patch instances |
texts | A list of Text instances |
xaxis | A matplotlib.axis.XAxis instance |
yaxis | A matplotlib.axis.YAxis instance |
Axis containers
Axis 实例处理刻度线, 网格线, 刻度标签, 轴标签的绘制. Locator 和 Formatter 控制刻度放在哪里和怎样作为字符串展示出来.
每个 Axis 对象都有一个 label 属性和一个 major 刻度和 minor 刻度的列表. 刻度是 axis.XTick 和 axis.YTick 实例, 他们包含了渲染刻度和刻度标签的实际的 line 和 text 原语.
因为刻度是按需动态创建的(例如当你 panning (平移)和 zooming(缩放) 的时候)
可以用 axis.Axis.get_major_ticks 和 axis.Axis.get_minor_ticks.获取刻度.
Axis 实例有访问器方法, 可以返回 刻度线, 刻度标签, 刻度位置等
accessor method 访问器方法, 返回私有变量的值.
mutator method 更改器方法
例
fig, ax = plt.subplots()
axis = ax.xaxis
axis.get_ticklocs()
#array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
axis.get_ticklabels()
#[Text(0.0, 0, '0.0'), Text(0.2, 0, '0.2'), Text(0.4, 0, '0.4'), Text(0.6000000000000001, 0, '0.6'), Text(0.8, 0, '0.8'), Text(1.0, 0, '1.0')]
axis.get_ticklines()
#<a list of 12 Line2D ticklines objects>
在上例中有 12 个刻度线只有 6 个标签, 因为默认上下都有刻度线, 但只有底部有标签.
通过设置 minor = True 来查看次要刻度线和次要刻度标签. 因为没有次要刻度, 所以返回值为空.
axis.get_ticklabels(minor=True)
#[]
axis.get_ticklines(minor=True)
#<a list of 0 Line2D ticklines objects>
下面是 Axis 的一些有用的访问器
Axis accessor method | Description | |
---|---|---|
get_scale | The scale of the Axis, e.g., ‘log’ or ‘linear’ | |
get_view_interval | The interval instance of the Axis view limits | |
get_data_interval | The interval instance of the Axis data limits | |
get_gridlines | A list of grid lines for the Axis | |
get_label | The Axis label - a Text instance | |
get_offset_text | The Axis offset text - a Text instance | |
get_ticklabels | A list of Text instances - keyword minor=True | False |
get_ticklines | A list of Line2D instances - keyword minor=True | False |
get_ticklocs | A list of Tick locations - keyword minor=True | False |
get_major_locator | The ticker.Locator instance for major ticks | |
get_major_formatter | The ticker.Formatter instance for major ticks | |
get_minor_locator | The ticker.Locator instance for minor ticks | |
get_minor_formatter | The ticker.Formatter instance for minor ticks | |
get_major_ticks | A list of Tick instances for major ticks | |
get_minor_ticks | A list of Tick instances for minor ticks | |
grid | Turn the grid on or off for the major or minor ticks | |
例 |
# plt.figure creates a matplotlib.figure.Figure instance
fig = plt.figure()
rect = fig.patch # a rectangle instance
rect.set_facecolor('lightgoldenrodyellow')
ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])
rect = ax1.patch
rect.set_facecolor('lightslategray')
for label in ax1.xaxis.get_ticklabels():
# label is a Text instance
label.set_color('red')
label.set_rotation(45)
label.set_fontsize(16)
for line in ax1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('green')
line.set_markersize(25)
line.set_markeredgewidth(3)
plt.show()
设置刻度线颜色
plt.tick_params(axis='y',colors='red')
# 设置y轴刻度线为红色, 如果不创建子图, 就会把刻度线和刻度值都给设置为红色
Tick containers
在从 Matplotlib 的 Figure、Axes、Axis 到 Tick 的过程中,matplotlib.axis.Tick 是最终的容器对象。Tick 包含刻度线和网格线实例,以及上下刻度线的标签实例。每个实例都可以直接访问,因为它们是 Tick 属性的一部分。
简单来说,Tick 是 Matplotlib 中用于控制刻度线的容器对象。除了 Tick 对象本身,还包含刻度线和网格线实例,以及与刻度线对应的标签实例。这些实例可以通过直接访问 Tick 对应的属性来进行设置,从而定制刻度线和标签的样式。
Tick attribute | Description |
---|---|
tick1line | A Line2D instance |
tick2line | A Line2D instance |
gridline | A Line2D instance |
label1 | A Text instance |
label2 | A Text instance |
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
# Use automatic StrMethodFormatter
ax.yaxis.set_major_formatter('${x:1.2f}')
ax.yaxis.set_tick_params(which='major', labelcolor='green',tick1On = False,tick2On = True,
labelleft=False, labelright=True)
plt.show()
valid keywords are ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', 'grid_agg_filter', 'grid_alpha', 'grid_animated', 'grid_antialiased', 'grid_clip_box', 'grid_clip_on', 'grid_clip_path', 'grid_color', 'grid_dash_capstyle', 'grid_dash_joinstyle', 'grid_dashes', 'grid_data', 'grid_drawstyle', 'grid_figure', 'grid_fillstyle', 'grid_gid', 'grid_in_layout', 'grid_label', 'grid_linestyle', 'grid_linewidth', 'grid_marker', 'grid_markeredgecolor', 'grid_markeredgewidth', 'grid_markerfacecolor', 'grid_markerfacecoloralt', 'grid_markersize', 'grid_markevery', 'grid_path_effects', 'grid_picker', 'grid_pickradius', 'grid_rasterized', 'grid_sketch_params', 'grid_snap', 'grid_solid_capstyle', 'grid_solid_joinstyle', 'grid_transform', 'grid_url', 'grid_visible', 'grid_xdata', 'grid_ydata', 'grid_zorder', 'grid_aa', 'grid_c', 'grid_ds', 'grid_ls', 'grid_lw', 'grid_mec', 'grid_mew', 'grid_mfc', 'grid_mfcalt', 'grid_ms']