【问题标题】:Error when trying to label x and y axis in Pandas horizontal bar graph尝试在 Pandas 水平条形图中标记 x 和 y 轴时出错
【发布时间】:2019-07-18 01:59:17
【问题描述】:

我正在尝试在水平条形图上设置 x 和 y 标签,但出现此错误。请帮助我完成它。

这是我的图表代码:

alt_method[['Jan_avg','Jan_count']].sort_values(by=['Jan_avg','Jan_count'],ascending=True).plot.barh(xlim = (0,60000),ylim = (6300.0,64289.0))

alt_method.set_xlabel('Shipment')

这是我的错误信息:

AttributeError: 'DataFrame' object has no attribute 'set_xlabel'

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    alt_method 是一个数据帧。您可以使用.plot() 绘制DataFrame,但要设置轴标签,您应该使用matplotlib.pyplot(通常缩写为plt)提供的绘图命令:

    import matplotlib.pyplot as plt
    
    df.plot() # per your code
    plt.ylabel('ylabel goes here')
    plt.show()
    

    一个可重现的例子:

    df = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/fpp2/goog200.csv", index_col=0)
    df['value'].plot()
    plt.ylabel('price')
    plt.xlabel('time')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      另一种方法是抓取plot返回的轴句柄,然后将标签设置为

      ax = alt_method[['Jan_avg','Jan_count']].sort_values(by=['Jan_avg','Jan_count'],ascending=True).plot.barh(xlim = (0,60000),ylim = (6300.0,64289.0))
      
      ax.set_xlabel('Shipment')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-07
        • 2015-11-11
        • 2013-11-22
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        • 2020-03-20
        相关资源
        最近更新 更多