假设我想在 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])
关于python - 使用 pandas 的绘图方法在 1 行中绘制图表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502829/