Artist概述
Matplotlib作图与人工作图步骤基本一致,都是创建画布,然后使用画笔、渲染工具等组件进行绘制作图。
Artist对象用来对画布进行渲染。Matplotlib有三层API:
- matplotlib.backend_bases.FigureCanvas:绘图区
- matplotlib.backend_bases.Renderer:渲染器,控制如何在画布上绘图
- matplotlib.artist.Artist:具体组件,调用renderer在画布上绘图
FigureCanvas和Renderer处理与用户(底层)接口交互的细节,而Artist处理上层结构如图像、文本、线条的绘制与展现。因此作图者主要使用Artist工具。
Artist可分为两类,分别是primitive和container:
primitive:作图基本要素,代表在画布上作图使用的标准图形对象,包括 Line2D(二维曲线)、Rectangle(矩形)、Text(文本)、AxesImage等;
container:装primitive基本要素的容器,包括Axis、Axes、Figure。container组件关系图如下:
Artist标准使用步骤如下:
Axes是Matplotlib API最重要的类,因此作图者使用最多的就是它。大多数作图组件都在Axes区域内进行绘图,Axes有许多专用的辅助方法(plot()、text()、hist()、imshow())来创建最常用的图primitive(Line2D、Text、Rectangle、AxesImage)。这些辅助方法可以获取数据并在需要时创建Artist实例,并且可以将Artist添加到相关容器中,在需要的时候进行绘制。
官网上的示例代码:
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() # 实例化Figure fig.subplots_adjust(top=0.8) # 调整子图的布局参数 ax1 = fig.add_subplot(211) # 添加子图 ax1.set_ylabel('volts') # 设置y轴标签 ax1.set_title('a sine wave') # 设置标题 t = np.arange(0.0, 1.0, 0.01) # 设置自变量范围 s = np.sin(2*np.pi*t) # 创建关于自变量t的正弦函数s 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]) # 添加Axes(参数为序列,表示[左,底,宽,高]) n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='yellow') # 绘制直方图 ax2.set_xlabel('time (s)') # 设置x轴标签 plt.show() # 显示图形
相关函数API文档传送:plt.figure()、fig.subplots_adjust()、fig.add_subplot()、ax.plot()、fig.add_axes()、ax.set_ylabel()
常见的Artist辅助类在官网已有总结,如下表(第一列表示辅助方法,第二列表示该方法所属Artist类,第三列表示容器):
Axes helper method | Artist | Container |
---|---|---|
annotate - text annotations | ax.texts | |
bar - bar charts | ax.patches | |
errorbar - error bar plots | ax.lines and ax.patches | |
fill - shared area | ax.patches | |
hist - histograms | ax.patches | |
imshow - image data | ax.images | |
legend - Axes legends | ax.legends | |
plot - xy plots | ax.lines | |
scatter - scatter charts | ax.collections | |
text - text | ax.texts |
(由于本次任务较多,因此分多次笔记)
Task2后续笔记(更新中):
数据可视化笔记 Task2 - Artist“艺术画笔”(二)
参考资料
[1] Datawhale数据可视化开源小组. Fantastic-Matplotlib, 第二回:艺术画笔见乾坤.
[2] Matplotlib 3.5.1 Documentation——Tutorials-Artist tutorial