Matplotlib 填充 pandas DataFrame.plot 至 matplotlib subplot 中
Matplotlib 和 pandas 是 Python 数据科学领域非常重要的两个库。Matplotlib 是一个灵活但复杂的绘图工具箱,而 pandas 则提供了分析结构化数据所需的数据结构和工具。其中,Matplotlib 的最大优点是可以适应各种数据可视化需求。pandas DataFrame.plot 是十分常用而又易于使用的绘图工具,而将它完美地填充进 Matplotlib 的 subplot 中,可以更加灵活地进行可视化操作。本篇文章将介绍如何完成这个过程。
阅读更多:Matplotlib 教程
创建 DataFrame 并绘制基础图像
首先,我们来创建一个数据框并制作一个基础图像:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 创建数据框
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
# 绘制图形
df.plot()
plt.show()
这段代码将生成一个基础折线图,其中横轴为 index 列(在这个例子中展示为 0 到 9 的整数),纵轴为值。图像如下:
a b c d
0 0.336042 0.387177 0.138054 0.747102
1 0.757594 0.308674 0.653717 0.442413
2 0.550085 0.090298 0.318145 0.013404
3 0.949858 0.606628 0.188200 0.740288
4 0.497361 0.629171 0.794210 0.188957
5 0.107617 0.931826 0.196816 0.506546
6 0.880798 0.967466 0.047677 0.400492
7 0.177550 0.857575 0.741217 0.317822
8 0.175665 0.680328 0.284675 0.065003
9 0.228307 0.019244 0.424322 0.239988
将 DataFrame.plot 填充至 Matplotlib subplot 中
现在,我们需要把这个图像放进一个 Matplotlib subplot 中。为了做到这一点,我们需要掌握如下三种方式:
- 在单个 subplot 中绘制 DataFrame.plot;
- 在多个 subplot 中绘制 DataFrame.plot;
- 在相邻 subplot 中绘制 DataFrame.plot。
方式一:在单个 subplot 中绘制
如果您只想在单个 subplot 中绘制 DataFrame.plot,那么可以采用直接绘制的方式,例如:
fig, ax = plt.subplots()
df.plot(ax=ax)
plt.show()
在这种情况下,图形将与以前相同。您将额外得到一个 fig 对象和一个 ax 对象。这是因为 plt.subplots() 命令实际上是用一个单元格创建了 fig 和 ax 对象(也称为“子图对象”)。
方式二:在多个 subplot 中绘制
如果您想在多个 subplot 中绘制 DataFrame.plot,则需要创建一个 ax 对象列表。例如,下面的代码将创建一个 2×2 的 subplot,并将 DataFrame 绘制到第一个 subplot 上:
fig, axs = plt.subplots(2, 2)
df.plot(ax=axs[0, 0])
plt.show()
在这个例子中,axs[0, 0] 是 Matplotlib subplot 对象,在这里,我们用 DataFrame.plot 填充它。另外三个 subplot 将保留为空白,您可以调用不同的命令将其他图形填充其中。
方式三:在相邻 subplot 中绘制
在 Matplotlib 中,可以在与它相邻的子图中绘制 DataFrame.plot。为了具体说明,我们来看下面的代码:
fig, ax = plt.subplots(2, 1)
df['a'].plot(ax=ax[0], color='b')
df['b'].plot(ax=ax[1], color='r')
plt.show()
这个例子展示了如何将一个 DataFrame 的多列绘制在相邻 subplot 中。由于我们正在将两个不同的图形拟合到不同的 subplot 中,因此这里我们需要分别调用 DataFrame.plot 两次。其中,df[‘a’] 和 df[‘b’] 分别是 DataFrame 中的不同列。在这个例子里,我们还指定了线条的颜色。
添加其他 Matplotlib 批注
如果您在将 DataFrame.plot 合并到 Matplotlib subplot 中时希望向图表中添加其他信息,可以使用 Matplotlib 提供的其他注释工具。例如,您可以添加标题或轴标签等注释。
下面的代码展示了如何添加标题和横轴标签:
fig, ax = plt.subplots()
df.plot(ax=ax)
ax.set_title('Title')
ax.set_xlabel('X Label')
plt.show()
在这个例子中,我们调用了 ax.set_title() 方法设置了标题,并使用 ax.set_xlabel() 方法设置了横轴标签。
总结
本篇文章介绍了如何将 pandas DataFrame.plot 合并到 Matplotlib subplot 中,并演示了三种不同的方法。在实际应用中,常常需要通过添加其他的批注来进一步完善图表,并展示更加详尽的分析结果。
极客教程