estebanpdl estebanpdl - 22 days ago 5
Python Question

How to display years on x axis line plot?

I'm trying to plot some data using

pandas
and
matplotlib
.

Consider this data:

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]


if I plot the data:

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


Everything goes ok as image:

enter image description here

However, if try a period less than 11 years
x axis
doesn't display years:

Fo example, consider this data:

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)


It shows:

enter image description here

Is there a solution, maybe some argument or parameter I missing, in order to display years from 2008 to 2015 and not the index as single number?

Thanks in advance!

Answer

The easiest way to fix your problem is to explicitly use datetime objects as your index. Pandas provides a utility for this:

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

The freq parameter takes an offset. You can create your own or use one of the built-in aliases.