简介
Matplotlib 是一个用于 Python 编程语言及其数值数学扩展 NumPy 的绘图库。本教程将重点介绍 Matplotlib 中的文本对齐。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。
创建一个矩形
我们将通过使用 matplotlib.patches 模块中的 Rectangle() 函数在绘图中创建一个矩形。创建矩形后,我们将使用 set_xlim() 和 set_ylim() 函数设置其水平和垂直界限。最后,我们将把矩形添加到绘图中。
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
## Build a rectangle in axes coords
left, width =.25,.5
bottom, height =.25,.5
right = left + width
top = bottom + height
p = Rectangle((left, bottom), width, height, fill=False)
ax.add_patch(p)
## Set the horizontal and vertical limits
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
向矩形添加文本
在这一步中,我们将使用 text() 函数向矩形添加文本。文本的水平和垂直对齐方式将分别使用 horizontalalignment 和 verticalalignment 参数进行设置。
## Add text to the rectangle
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top),'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.show()
自定义绘图
在这一步中,我们将通过添加轴标签和移除轴线来自定义绘图。
## Customize the plot
ax.set_axis_off()
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Text Alignment in Matplotlib')
plt.show()
总结
在本教程中,我们学习了如何在 Matplotlib 中对齐文本。我们使用 text() 函数向矩形添加文本,并分别使用 horizontalalignment 和 verticalalignment 参数设置水平和垂直对齐方式。我们还通过添加轴标签和移除轴线来自定义绘图。