Matplotlib 阶梯直方图教程

PythonPythonBeginner
立即练习

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

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

简介

Matplotlib 是 Python 中的一个数据可视化库。它被广泛用于创建各种可视化图表,如折线图、散点图、柱状图、直方图等等。本教程将专注于使用 Matplotlib 创建分步直方图。

虚拟机使用提示

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

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

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

导入必要的库和模块

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import StepPatch

准备数据

np.random.seed(0)
h, edges = np.histogram(np.random.normal(5, 3, 5000),
                        bins=np.linspace(0, 10, 20))

创建一个简单的阶梯直方图

plt.stairs(h, edges, label='Simple histogram')
plt.legend()
plt.show()

修改阶梯直方图的基线

plt.stairs(h, edges + 5, baseline=50, label='Modified baseline')
plt.legend()
plt.show()

创建一个没有边界的阶梯直方图

plt.stairs(h, edges + 10, baseline=None, label='No edges')
plt.legend()
plt.show()

创建一个填充直方图

plt.stairs(np.arange(1, 6, 1), fill=True,
              label='Filled histogram\nw/ automatic edges')
plt.legend()
plt.show()

创建一个带阴影线的直方图

plt.stairs(np.arange(1, 6, 1)*0.3, np.arange(2, 8, 1),
              orientation='horizontal', hatch='//',
              label='Hatched histogram\nw/ horizontal orientation')
plt.legend()
plt.show()

创建一个 StepPatch 艺术家对象

patch = StepPatch(values=[1, 2, 3, 2, 1],
                  edges=range(1, 7),
                  label=('Patch derived underlying object\n'
                         'with default edge/facecolor behaviour'))
plt.gca().add_patch(patch)
plt.xlim(0, 7)
plt.ylim(-1, 5)
plt.legend()
plt.show()

创建堆叠直方图

A = [[0, 0, 0],
     [1, 2, 3],
     [2, 4, 6],
     [3, 6, 9]]

for i in range(len(A) - 1):
    plt.stairs(A[i+1], baseline=A[i], fill=True)
plt.show()

比较 .pyplot.step.pyplot.stairs

bins = np.arange(14)
centers = bins[:-1] + np.diff(bins) / 2
y = np.sin(centers / 2)

plt.step(bins[:-1], y, where='post', label='step(where="post")')
plt.plot(bins[:-1], y, 'o--', color='grey', alpha=0.3)

plt.stairs(y - 1, bins, baseline=None, label='stairs()')
plt.plot(centers, y - 1, 'o--', color='grey', alpha=0.3)
plt.plot(np.repeat(bins, 2), np.hstack([y[0], np.repeat(y, 2), y[-1]]) - 1,
         'o', color='red', alpha=0.2)

plt.legend()
plt.title('step() vs. stairs()')
plt.show()

总结

本教程涵盖了使用Matplotlib创建阶梯直方图的基础知识。我们学习了如何创建简单的阶梯直方图、修改直方图的基线、创建填充和带阴影线的直方图以及创建堆叠直方图。我们还比较了 .pyplot.step.pyplot.stairs 之间的差异。