使用 pandas 中的 plot 方法在 1 行中绘制图形时出现问题

Problem with plotting graphs in 1 row using plot method from pandas

假设我想在 1 行中绘制 3 个图形:来自其他 3 个特征的依赖关系 cnt

代码:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
    df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[0, idx])
plt.show()

错误信息:

IndexErrorTraceback (most recent call last)
<ipython-input-697-e15bcbeccfad> in <module>()
      2 fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
      3 for idx, feature in enumerate(min_regressors):
----> 4     df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[0, idx])
      5 plt.show()

IndexError: too many indices for array

但是当我在 (2,2) 维度上绘图时一切正常:

代码:

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
    df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[idx / 2, idx % 2])
plt.show()

输出:

我正在使用 python 2.7

问题与 pandas 无关。您看到的索引错误来自 ax= axes[0, idx]。这是因为你只有一行。 [0, idx] 当你有多行时会起作用。

对于一行,您可以跳过第一个索引并使用

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
for idx, feature in enumerate(min_regressors):
    df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax= axes[idx])
plt.show()

回顾一下

正确

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8, 3))
axes[0].plot([1,2], [1,2])

不正确

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8, 3))
axes[0, 0].plot([1,2], [1,2])

正确

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8, 3))
axes[0,0].plot([1,2], [1,2])

为了让您了解和理解正在发生的事情,我建议您在这两种情况下检查 axes 的大小。您会看到,当 nrowsncols 为 1 时,轴变量将为一维,否则将为二维。

您无法按照您的方式为一维对象编制索引 (ax= axes[0, idx])。

你可以做的是使用 numpy 的 atleast_2d 使轴成为二维的。

或者,更好的解决方案是直接迭代特征和轴:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))
for ax, feature in zip(axes, min_regressors):
    df_shuffled.plot(feature, "cnt", subplots=True, kind="scatter", ax=ax)
plt.show()