使用数据框的切片时如何使子图正常工作

How to make subplots work correctly when working with slices of a data frame

我正在尝试绘制 4 个子图,将大数据框分成较小的部分,这样条形图就不会过于庞大和难以阅读。我已将切片分开并将它们分别分配给单独的数据帧。我正在使用的数据框如下所示(此数据框是多索引数据框 (df.unstack()) 的 unstack 输出):

Age Range   40-49  50-59  60-69  70-79  80+
County                                     
Allen         NaN    NaN    NaN    NaN  1.0
Athens        NaN    NaN    1.0    NaN  NaN
Belmont       NaN    1.0    NaN    1.0  1.0
Clark         NaN    NaN    NaN    1.0  NaN
Columbiana    NaN    NaN    NaN    1.0  NaN
Cuyahoga      NaN    3.0    1.0    7.0  3.0
Defiance      NaN    NaN    NaN    NaN  1.0
Franklin      NaN    NaN    4.0    1.0  3.0
Greene        NaN    NaN    1.0    NaN  NaN
Hamilton      NaN    1.0    2.0    1.0  7.0
Hocking       NaN    NaN    NaN    1.0  NaN
Knox          NaN    NaN    NaN    NaN  1.0
Lorain        NaN    NaN    NaN    2.0  NaN
Lucas         NaN    NaN    1.0    NaN  2.0
Madison       1.0    NaN    NaN    NaN  NaN
Mahoning      NaN    1.0    NaN    1.0  2.0
Medina        NaN    1.0    NaN    NaN  NaN
Miami         NaN    NaN    1.0    NaN  1.0
Pickaway      NaN    NaN    NaN    1.0  NaN
Portage       1.0    NaN    NaN    2.0  NaN
Ross          NaN    NaN    NaN    1.0  NaN
Seneca        NaN    NaN    NaN    NaN  1.0
Shelby        NaN    NaN    NaN    NaN  1.0
Stark         NaN    NaN    NaN    1.0  NaN
Summit        NaN    NaN    NaN    1.0  NaN
Trumbull      NaN    NaN    NaN    1.0  1.0
Warren        NaN    1.0    NaN    NaN  2.0

我使用以下代码将它们分成 4 个相等的切片并将它们分配给各个数据帧:

df1 = df.unstack()[:7]
df2 = df.unstack()[7:14]
df3 = df.unstack()[14:21]
df4 = df.unstack()[21:]

然后我使用以下代码将它们绘制为子图:

plt.subplot(221)
df1.plot(kind='bar')

plt.subplot(222)
df2.plot(kind='bar')

plt.subplot(223)
df3.plot(kind='bar')

plt.subplot(224)
df4.plot(kind='bar')

plt.show()

当我 运行 此代码时,它输出四个空白子图(它们采用 4 行 1 列格式),然后在这四个之后它仅绘制最后一个子图 (df4)。如果我注释掉 plt.subplot() 行,则绘图会正确输出。我以前用类似的格式绘制过类似的东西,所以我不确定为什么这不会 运行 以同样的方式,它可能与使用切片有关吗?

要在 matplotlib 子图上绘制 pandas.DataFrame,您需要:

  1. plt.subplot() 调用返回的轴存储到一个变量中,然后您可以
  2. 将这个轴传递给pandas.DataFrame.plot()调用

喜欢:

ax1 = plt.subplot(221)
df1.plot(kind='bar', ax = ax1)

因为你没有这样做,每个新的 plt.subplot() 调用都会创建新的图形并覆盖 pandas.DataFrame.plot() 调用创建的图形,因此你会得到 4 个空图和一个来自 df4.plot(kind='bar')

你应该做什么:

ax1 = plt.subplot(221)
df1.plot(kind='bar', ax = ax1)

ax2 = plt.subplot(222)
df2.plot(kind='bar', ax = ax2)

ax3 = plt.subplot(223)
df3.plot(kind='bar', ax = ax3)

ax4 = plt.subplot(224)
df4.plot(kind='bar', ax = ax4)

plt.show()

使用 DataFrame 的前两列的示例输出: