Matplotlib 椭圆集合

PythonPythonBeginner
立即练习

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

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

简介

Matplotlib 是 Python 中一个强大的数据可视化库。在本实验中,我们将探索如何使用 EllipseCollection 来绘制一组椭圆。

虚拟机使用提示

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) 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") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("Numerical Computing") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48697{{"Matplotlib 椭圆集合"}} matplotlib/figures_axes -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/tuples -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/importing_modules -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/using_packages -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/standard_libraries -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/numerical_computing -.-> lab-48697{{"Matplotlib 椭圆集合"}} python/data_visualization -.-> lab-48697{{"Matplotlib 椭圆集合"}} end

导入必要的库

我们将首先导入必要的库。

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.collections import EllipseCollection

为椭圆创建数据

我们以 x 坐标、y 坐标、宽度、高度和角度的数组形式为椭圆创建数据。

x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)

XY = np.column_stack((X.ravel(), Y.ravel()))

ww = X / 10.0
hh = Y / 15.0
aa = X * 9

创建椭圆集合

我们使用上述数据创建一个 EllipseCollection,并将单位指定为 'x',偏移量指定为 XY

fig, ax = plt.subplots()

ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
                       offset_transform=ax.transData)

设置椭圆的颜色

我们根据 EllipseCollection 中每个椭圆的 x 坐标与 y 坐标之和来设置其颜色。

ec.set_array((X + Y).ravel())

将集合添加到绘图中

我们将 EllipseCollection 添加到绘图中。

ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()

总结

在本实验中,我们学习了如何使用 EllipseCollection 在 Matplotlib 中绘制椭圆集合。我们还学习了如何根据每个椭圆的 x 和 y 坐标来设置其颜色。