【问题标题】:Pandas: Number of passed axes does not match the number of columns to plotPandas:传递的轴数与要绘制的列数不匹配
【发布时间】:2018-07-26 17:42:33
【问题描述】:

我想将 pandas 数据框的三列绘制为 2x2 子图布局:

rand=np.random.random((12,6))
df=pd.DataFrame(columns=['a','b','c','d','e','f'],data=rand)
ax=df.loc[:,'a':'c'].plot(subplots=True,layout=(2,2))

这给了我想要的结果(右下角有一个空图)。但是,如果我尝试使用

向所有这些子图添加另一列
df.loc[:,'d':'f'].plot(subplots=True,ax=ax)

出现以下错误:

ValueError: The number of passed axes must be 3, the same as the output plot

有什么办法可以解决这个问题而不必重新排列子图的布局?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    如果发生

    ax=df.plot(subplots=True,layout=(2,2))
    

    ax 是一个包含 4 个元素的 2x2 数组。这些是 4 个轴,如果 df 仅包含 3 列,则最后一个轴是不可见的。再次绘制 3 列时,您需要提供 3 个轴,而不是全部 4 个。一个选项是将 ax 数组索引到要使用的列数。

    df2.plot(subplots=True,ax=ax.flatten()[:3])
    

    完整示例:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    rand=np.random.random((12,6))
    df=pd.DataFrame(columns=['a','b','c','d','e','f'],data=rand)
    
    ax=df.loc[:,'a':'c'].plot(subplots=True,layout=(2,2))
    df.loc[:,'d':'f'].plot(subplots=True,ax=ax.flatten()[:3])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多