Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set xlim for pandas/matplotlib where index is string

I have a pandas dataframe that uses strings as index. How can I set xlim for the x axis when my dataframe index is of type object? I tried adding two additional years one at the end and one at the beginning where all datasets are np.nan but that didn't work.

Here is the dataframe

Dataframe

The datatype of index is object

df.index
Out[52]: Index(['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'], dtype='object')

Here is the plot

Matplotlib Plot

So I would like to have some extra space on the x-axis in so the values for the fist and last year are better visible. What could I do?

EDIT:

Here is a minimal example using objects and not date objects as index

ipython notebook

like image 662
Christian Rapp Avatar asked Dec 03 '25 01:12

Christian Rapp


1 Answers

Use set_xlim, +1 means moving 1 unit to the right and -1 means the reverse. In the following example I expanded the plot 0.5 months each side:

df=pd.DataFrame({'A': range(10), 'B': range(1, 11), 'C': range(2,12)})
df.index=pd.date_range('2001/01/01', periods=10, freq='M')
ax=df.plot(kind='line')
ax.set_xlim(np.array([-0.5, 0.5])+ax.get_xlim())

enter image description here

Edit, to have xticklabel for every year, instead the default every two years in pandas:

ax=df.plot(kind='line', xticks=df.index)
ax.set_xticklabels(df.index.map(lambda x: datetime.datetime.strftime(x, '%Y')))

enter image description here

like image 121
CT Zhu Avatar answered Dec 05 '25 15:12

CT Zhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!