首页 > 解决方案 > 无法使用 subplot 命令组合绘图

问题描述

我有以下简单的熊猫数据框:

   A  B  C   D
0  1  8  9  50
1  5  4  1  70
2  7  2  4  90

以下代码用于一个接一个地绘制单独的图形:

df.drop("D", axis=1).plot(kind='bar')
plt.show()

df['D'].plot(kind='bar')
plt.show()

但是,我无法使用suplot命令将这些组合成一个图形:

plt.subplot(211)
df.drop("D", axis=1).plot(kind='bar')

plt.subplot(212)
df['D'].plot(kind='bar')

plt.show()

以下代码生成 2 个图,但只有一个图。没有错误信息。哪里有问题?

标签: pythonpandasmatplotlib

解决方案


当您调用 时df.plot,您可以指定要在哪些轴上绘图。

ax1 = plt.subplot(121)
df.drop("D", axis=1).plot(kind='bar', ax=ax1)

ax2 = plt.subplot(122)
df['D'].plot(kind='bar', ax=ax2)

plt.show()

显示两个图:

在此处输入图像描述


推荐阅读