【问题标题】:How to display years on x axis line plot?如何在 x 轴线图上显示年份?
【发布时间】:2016-11-17 21:02:57
【问题描述】:

我正在尝试使用pandasmatplotlib 绘制一些数据。

考虑这些数据:

years = [i for i in range(2005, 2016)]
values = [49.929266640000002, 45.441518010000003, 49.762879810000001, 52.849612180000001, 57.618790150000002, 47.750615240000002, 47.508212309999998, 37.414841590000002, 45.441518010000003, 47.750615240000002, 49.929266640000002]

如果我绘制数据:

lineplt = pandas.Series(values, name='Some City 2005 - 2015')
lineplt.index = years
lineplt.plot(title = 'Rate some city 2005 - 2015', legend=True)

一切正常:

但是,如果尝试小于 11 年的时间段 x axis 不会显示年份:

例如,考虑以下数据:

years = [i for i in range(2008, 2016)]
values = [49.929266640000002, 45.441518010000003, 49.762879810000001, 52.849612180000001, 57.618790150000002, 47.750615240000002, 47.508212309999998, 37.414841590000002]
lineplt = pandas.Series(values, name='Some city 2008 - 2015')
lineplt.index = years
lineplt.plot(title = 'Rate some city 2008 - 2015', legend=True)

它显示:

是否有解决方案,可能是我遗漏了一些参数或参数,以便将 2008 年至 2015 年的年份而不是索引显示为单个数字?

提前致谢!

【问题讨论】:

    标签: python python-3.x pandas matplotlib jupyter


    【解决方案1】:

    解决问题的最简单方法是明确使用datetime 对象作为索引。 Pandas 为此提供了一个实用程序:

    years = pd.date_range('2008','2015', freq='AS')
    

    freq 参数采用偏移量。您可以创建自己的或使用built-in aliases 之一。

    【讨论】:

    • 谢谢!很容易。我做了:lineplt.index = pandas.date_range('2008','2015', freq='AS'),效果很好!
    • @estebanpdl 是的,我经常参考那个链接。
    【解决方案2】:

    你应该使用类似的东西:

    fig = plt.figure()                                                               
    ax = fig.add_subplot(1,1,1)    
    
    ax.get_xaxis().get_major_formatter().set_useOffset(False)
    ax.set_xlim((2008, 2016))
    

    【讨论】:

    • 谢谢,瓦夏。这次我会去找第一个答案。就一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多