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

标签 python pandas matplotlib plot subplot

假设我想在 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()

输出:

enter image description here

我正在使用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/

相关文章:

python pandas 在迭代期间更新与先前更新的行相关的列值

python - 在 python 上反转 3D 网格

python - 在 pylab.plot 中使用数据框列名作为标签

python - Matplotlib:绘制饼图,楔形分解成条形图

python - pandas DataFrame 如何混合不同比例的条形图和线图

python - 为什么计算器会崩溃

python - 将值四舍五入为最接近的可被 2、4、8 和 16 整除的数字?

python - 为什么使用 pandas.read_json 读取字符串整数不正确?

python - 根据来自不同数据框的两列条件乘以列?

python - pandas、polars 或 torch 中函数的高效迭代和应用?偷懒可能吗?