【问题标题】:Problem with plotting graphs in 1 row using plot method from pandas使用 pandas 的绘图方法在 1 行中绘制图形的问题
【发布时间】:2019-06-26 23:31:16
【问题描述】:

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

代码:

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

【问题讨论】:

    标签: python pandas matplotlib plot subplot


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      您无法按照自己的方式索引一维对象 (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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 2021-11-09
        • 1970-01-01
        相关资源
        最近更新 更多