艺术家介绍#

Matplotlib 图表上您几乎所有与之交互的对象都被称为“艺术家”(并且是 Artist 类的子类)。FigureAxes 都是艺术家,通常包含 Axis 艺术家以及包含数据或注释信息的艺术家。

创建艺术家#

通常我们不直接实例化艺术家,而是使用 Axes 上的绘图方法。下面给出了一些绘图方法及其创建的艺术家对象的示例:

Axes 辅助方法

艺术家

annotate - 文本注释

Annotation

bar - 条形图

Rectangle

errorbar - 误差棒图

Line2DRectangle

fill - 填充区域

Polygon

hist - 直方图

Rectangle

imshow - 图像数据

AxesImage

legend - Axes 图例

Legend

plot - xy 散点图

Line2D

scatter - 散点图

PolyCollection

text - 文本

文本

例如,我们可以保存从 axes.Axes.plot 返回的 Line2D 艺术家

In [209]: import matplotlib.pyplot as plt
In [210]: import matplotlib.artist as martist
In [211]: import numpy as np

In [212]: fig, ax = plt.subplots()
In [213]: x, y = np.random.rand(2, 100)
In [214]: lines = ax.plot(x, y, '-', label='example')
In [215]: print(lines)
[<matplotlib.lines.Line2D at 0xd378b0c>]

请注意,plot 返回一个线条的 _列表_,因为您可以传入多个 x、y 对进行绘制。该线条已被添加到 Axes 中,我们可以通过 get_lines() 检索该艺术家。

In [216]: print(ax.get_lines())
<a list of 1 Line2D objects>
In [217]: print(ax.get_lines()[0])
Line2D(example)

更改艺术家属性#

获取 lines 对象使我们能够访问 Line2D 对象的所有属性。因此,如果我们想事后更改线宽,可以使用 Artist.set 来实现。

fig, ax = plt.subplots(figsize=(4, 2.5))
x = np.arange(0, 13, 0.2)
y = np.sin(x)
lines = ax.plot(x, y, '-', label='example', linewidth=0.2, color='blue')
lines[0].set(color='green', linewidth=2)

(源代码, 2x.png, png)

我们可以使用 matplotlib.artist.getp 查询所有可设置属性的完整列表

In [218]: martist.getp(lines[0])
agg_filter = None
alpha = None
animated = False
antialiased or aa = True
bbox = Bbox(x0=0.004013842290585101, y0=0.013914221641967...
children = []
clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
clip_on = True
clip_path = None
color or c = blue
dash_capstyle = butt
dash_joinstyle = round
data = (array([0.91377845, 0.58456834, 0.36492019, 0.0379...
drawstyle or ds = default
figure = Figure(550x450)
fillstyle = full
gapcolor = None
gid = None
in_layout = True
label = example
linestyle or ls = -
linewidth or lw = 2.0
marker = None
markeredgecolor or mec = blue
markeredgewidth or mew = 1.0
markerfacecolor or mfc = blue
markerfacecoloralt or mfcalt = none
markersize or ms = 6.0
markevery = None
mouseover = False
path = Path(array([[0.91377845, 0.51224793],        [0.58...
path_effects = []
picker = None
pickradius = 5
rasterized = False
sketch_params = None
snap = None
solid_capstyle = projecting
solid_joinstyle = round
tightbbox = Bbox(x0=70.4609002763619, y0=54.321277798941786, x...
transform = CompositeGenericTransform(     TransformWrapper(  ...
transformed_clip_path_and_affine = (None, None)
url = None
visible = True
window_extent = Bbox(x0=70.4609002763619, y0=54.321277798941786, x...
xdata = [0.91377845 0.58456834 0.36492019 0.03796664 0.884...
xydata = [[0.91377845 0.51224793]  [0.58456834 0.9820474 ] ...
ydata = [0.51224793 0.9820474  0.24469912 0.61647032 0.483...
zorder = 2

请注意,大多数艺术家也有一组独特的设置器;例如 Line2D.set_colorLine2D.set_linewidth

更改艺术家数据#

除了颜色线宽等样式属性外,Line2D 对象还具有数据属性。您可以使用 Line2D.set_data 在线条创建后设置数据。这通常用于动画,其中同一条线条随时间演变(参见 使用 Matplotlib 进行动画

fig, ax = plt.subplots(figsize=(4, 2.5))
x = np.arange(0, 13, 0.2)
y = np.sin(x)
lines = ax.plot(x, y, '-', label='example')
lines[0].set_data([x, np.cos(x)])

(源代码, 2x.png, png)

手动添加艺术家#

并非所有艺术家都有辅助方法,或者您可能出于某种原因想要使用低级方法。例如,patches.Circle 艺术家没有辅助方法,但我们仍然可以使用 axes.Axes.add_artist 方法创建并添加到 Axes 中

import matplotlib.patches as mpatches

fig, ax = plt.subplots(figsize=(4, 2.5))
circle = mpatches.Circle((0.5, 0.5), 0.25, ec="none")
ax.add_artist(circle)
clipped_circle = mpatches.Circle((1, 0.5), 0.125, ec="none", facecolor='C1')
ax.add_artist(clipped_circle)
ax.set_aspect(1)

(源代码, 2x.png, png)

Circle 构造函数以圆心和半径作为参数;可选参数作为关键字参数传入。

请注意,当我们像这样手动添加艺术家时,它不一定会像大多数辅助方法那样调整轴限制,因此艺术家可能会被裁剪,就像上面 clipped_circle 补丁的情况一样。

有关其他补丁,请参阅 Matplotlib 艺术家参考

移除艺术家#

有时我们希望从图中移除某个艺术家,而无需从头开始重新指定整个图。大多数艺术家都有一个可用的 remove 方法,该方法会将艺术家从其 Axes 列表中移除。例如,lines[0].remove() 将移除上面示例中创建的 Line2D 艺术家。