如何在 x 轴线图上显示年份?
How to display years on x axis line plot?
我正在尝试使用 pandas
和 matplotlib
绘制一些数据。
考虑这个数据:
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 年的年份而不是索引作为单个数字?
提前致谢!
解决问题的最简单方法是明确使用 datetime
对象作为索引。 Pandas 为此提供了一个实用程序:
years = pd.date_range('2008','2015', freq='AS')
freq
参数取一个偏移量。您可以创建自己的或使用 built-in aliases.
之一
你应该使用类似的东西:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.get_xaxis().get_major_formatter().set_useOffset(False)
ax.set_xlim((2008, 2016))
我正在尝试使用 pandas
和 matplotlib
绘制一些数据。
考虑这个数据:
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 年的年份而不是索引作为单个数字?
提前致谢!
解决问题的最简单方法是明确使用 datetime
对象作为索引。 Pandas 为此提供了一个实用程序:
years = pd.date_range('2008','2015', freq='AS')
freq
参数取一个偏移量。您可以创建自己的或使用 built-in aliases.
你应该使用类似的东西:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.get_xaxis().get_major_formatter().set_useOffset(False)
ax.set_xlim((2008, 2016))