绘图的生命周期

PythonPythonBeginner
立即练习

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

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

简介

在本实验中,我们将使用 Matplotlib 探索绘图的生命周期。我们将从原始数据开始,最终保存一个定制的可视化结果。我们将学习如何创建绘图、控制其样式、自定义其外观、组合多个可视化结果以及将绘图保存到磁盘。

虚拟机提示

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

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

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

导入必要的模块

首先,我们需要导入所需的模块:Matplotlib 和 NumPy。

import matplotlib.pyplot as plt
import numpy as np

准备数据

我们将使用一个包含不同公司销售信息的示例数据集。以下是数据示例:

data = {'Barton LLC': 109438.50,
        'Frami, Hills and Schmidt': 103569.59,
        'Fritsch, Russel and Anderson': 112214.71,
        'Jerde-Hilpert': 112591.43,
        'Keeling LLC': 100934.30,
        'Koepp Ltd': 103660.54,
        'Kulas Inc': 137351.96,
        'Trantow-Barrows': 123381.38,
        'White-Trantow': 135841.99,
        'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)

创建绘图

我们将使用条形图可视化来展示销售数据。请按以下步骤操作:

  1. 使用 plt.subplots() 创建一个图形和一个轴对象。
fig, ax = plt.subplots()
  1. 使用轴对象的 barh() 方法绘制数据。
ax.barh(group_names, group_data)

自定义绘图样式

我们可以更改绘图的样式,使其在视觉上更具吸引力。请按以下步骤操作:

  1. 使用 print(plt.style.available) 打印可用样式列表。
print(plt.style.available)
  1. 选择一种样式并使用 plt.style.use(style_name) 应用它。
plt.style.use('fivethirtyeight')
  1. 让我们再次显示绘图。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)

自定义绘图外观

我们可以进一步自定义绘图的外观。请按以下步骤操作:

  1. 旋转x轴标签,使其更具可读性。
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
  1. 设置x轴和y轴的范围、标签以及标题。
ax.set(xlim=[-10000, 140000],
       xlabel='Total Revenue',
       ylabel='Company',
       title='Company Revenue')
  1. 再次显示绘图。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
       title='Company Revenue')

组合多个可视化元素

我们可以向可视化图形中添加其他绘图元素。请按以下步骤操作:

  1. 添加一条代表销售数据平均值的垂直线。
ax.axvline(group_mean, ls='--', color='r')
  1. 在图上标注新公司。
for group in [3, 5, 8]:
    ax.text(145000, group, "New Company", fontsize=10, verticalalignment="center")
  1. 调整绘图标题的位置。
ax.title.set(y=1.05)
  1. 完整代码如下所示。
fig, ax = plt.subplots(figsize=(8, 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

## Add a vertical line, here we set the style in the function call
ax.axvline(group_mean, ls='--', color='r')

## Annotate new companies
for group in [3, 5, 8]:
    ax.text(145000, group, "New Company", fontsize=10,
            verticalalignment="center")

## Now we move our title up since it's getting a little cramped
ax.title.set(y=1.05)

ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
       title='Company Revenue')

plt.show()

保存绘图

最后,我们可以将绘图保存到磁盘。请按以下步骤操作:

  1. 使用 print(fig.canvas.get_supported_filetypes()) 打印支持的文件格式。
print(fig.canvas.get_supported_filetypes())
  1. 使用 fig.savefig(file_path, transparent=False, dpi=80, bbox_inches="tight") 将图形保存为图像文件。取消注释此行以保存图形。
fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")

你可以使用左侧边栏中的文件资源管理器打开保存的图像文件。

总结

在本实验中,我们学习了使用Matplotlib的绘图生命周期。我们从创建绘图开始,控制其样式,自定义其外观,组合多个可视化元素,最后将绘图保存到磁盘。Matplotlib提供了广泛的自定义选项,以创建视觉上吸引人且信息丰富的绘图。