假设我要绘制图表3中1行:依赖从其他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
这个问题是不相关的大熊猫。你看指数误差来自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
的尺寸在这两种情况下。你会看到,当任nrows
或ncols
是1,轴变量是一维,否则这将是2维的。
你不能索引1维的对象,你正在做的方式(ax= axes[0, idx]
)。
你可以做的是使用numpy的的atleast_2d使轴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()