使用 Python 中的 Matplotlib 绘制形状

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用 Python 中的 Matplotlib 库绘制各种形状。Matplotlib 是一个用于 Python 编程语言及其数值数学扩展 NumPy 的绘图库。它提供了一个面向对象的 API,用于使用 Tkinter、wxPython、Qt 或 GTK 等通用 GUI 工具包将绘图嵌入到应用程序中。

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("Saving Figures to File") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} matplotlib/figures_axes -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} matplotlib/saving_figures -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} python/for_loops -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} python/lists -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} python/tuples -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} python/importing_modules -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} python/data_visualization -.-> lab-48554{{"使用 Python 中的 Matplotlib 绘制形状"}} end

导入库

在开始使用 Matplotlib 之前,我们需要导入必要的库。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.path as mpath

定义形状

我们将使用 Matplotlib 定义想要绘制的形状。在这个示例中,我们将绘制一个圆形、一个矩形、一个扇形、一个正多边形、一个椭圆、一个箭头、一个路径补丁和一个花式框补丁。

shapes = [
    mpatches.Circle((0, 0), 0.1, ec="none"),
    mpatches.Rectangle((-0.025, -0.05), 0.05, 0.1, ec="none"),
    mpatches.Wedge((0, 0), 0.1, 30, 270, ec="none"),
    mpatches.RegularPolygon((0, 0), 5, radius=0.1),
    mpatches.Ellipse((0, 0), 0.2, 0.1),
    mpatches.Arrow(-0.05, -0.05, 0.1, 0.1, width=0.1),
    mpatches.PathPatch(mpath.Path([(0, 0), (0.5, 0.5), (1, 0)], [1, 2, 2]), ec="none"),
    mpatches.FancyBboxPatch((-0.025, -0.05), 0.05, 0.1, ec="none",
                            boxstyle=mpatches.BoxStyle("Round", pad=0.02)),
]

绘制形状

现在,我们将通过遍历 shapes 列表并将它们添加到绘图中来使用 Matplotlib 绘制形状。

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.show()

自定义形状

我们可以通过设置各种属性(如颜色、边缘颜色和透明度)来自定义形状。

shapes = [
    mpatches.Circle((0, 0), 0.1, color='red', alpha=0.5),
    mpatches.Rectangle((-0.025, -0.05), 0.05, 0.1, ec="none", color='green', alpha=0.5),
    mpatches.Wedge((0, 0), 0.1, 30, 270, ec="none", color='blue', alpha=0.5),
    mpatches.RegularPolygon((0, 0), 5, radius=0.1, color='orange', alpha=0.5),
    mpatches.Ellipse((0, 0), 0.2, 0.1, color='purple', alpha=0.5),
    mpatches.Arrow(-0.05, -0.05, 0.1, 0.1, width=0.1, color='yellow', alpha=0.5),
    mpatches.PathPatch(mpath.Path([(0, 0), (0.5, 0.5), (1, 0)], [1, 2, 2]), ec="none", color='pink', alpha=0.5),
    mpatches.FancyBboxPatch((-0.025, -0.05), 0.05, 0.1, ec="none", color='brown', alpha=0.5,
                            boxstyle=mpatches.BoxStyle("Round", pad=0.02)),
]

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.show()

保存绘图

我们可以使用 savefig 函数将绘图保存为图像文件。

fig, ax = plt.subplots()
for shape in shapes:
    ax.add_artist(shape)
plt.xlim([-0.5, 1.5])
plt.ylim([-0.5, 1.5])
plt.axis('off')
plt.savefig('shapes.png')

总结

在这个实验中,我们学习了如何使用 Python 中的 Matplotlib 库绘制各种形状。我们学习了如何定义形状、绘制形状、自定义形状以及将绘图保存为图像文件。Matplotlib 提供了一个易于使用的 API 来绘制各种类型的图表,并且在数据可视化中被广泛使用。