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

2024-01-04

假设我想在 1 行中绘制 3 个图:依赖关系cnt来自其他 3 个功能。

Code:

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) 维度绘图时一切正常:

Code:

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()

Output:

我在用着python 2.7


该问题与熊猫无关。您看到的索引错误来自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()

作为回顾

Correct

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])

Correct

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8, 3))
axes[0,0].plot([1,2], [1,2])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pandas 的绘图方法在 1 行中绘制图表时出现问题 的相关文章

随机推荐