[Matplotlib-users] bar plot with datetime x axis
Steve Aplin
aplin.steve at gmail.com
Wed May 9 09:06:06 EDT 2018
Hello everyone,
Having a bit of an adventure controlling the display of the x axis when
plotting a pandas dataframe or series using pandas plot(), as in
df.plot(kind='bar') or s.plot(kind='bar').
Here's the head of one column:
1996-01-01 180.0
1997-01-01 159.0
1998-01-01 159.0
1999-01-01 152.0
2000-01-01 121.0
Name: column A, dtype: float64
... and here's its index:
DatetimeIndex(['1996-01-01', '1997-01-01', '1998-01-01', '1999-01-01',
'2000-01-01', ... ],
dtype='datetime64[ns]', freq=None)
I want to show a bunch of subplots, so my code looks like this:
> from datetime import datetime
> import matplotlib.pyplot as plt
> import pandas as pd
> import numpy as np
> import matplotlib.dates as mdates
> %matplotlib inline
>
> fig, axs = plt.subplots(9,2,figsize=(20,20),sharex=True)
> for i,col in enumerate(df):
> ax = df[col].plot(kind='bar',ax=axs[i,0])
>
etc.
... which gives an x tick value for each index item (i.e. each bar), in
full datetime format (YYYY-MM-DD 00:00:00), rotated 90 degrees.
I don't want full datetime format, I just want the year portion. Googling
the issue led me to trying this:
fig.autofmt_xdate()
>
... which rotates the labels, but still in full datetime format.
So I tried adding
> formatter = mdates.DateFormatter('%Y')
> ax.xaxis.set_major_formatter(formatter)
>
which throws this error:
ValueError: DateFormatter found a value of x=0, which is an illegal
date. This usually occurs because you have not informed the axis that
it is plotting dates, e.g., with ax.xaxis_date()
... which is a bit confusing, since the index is a pandas datetimeindex.
Any ideas about how I could get my xaxis to not show just the year portion?
Thanks in advance!
Stephen E. Aplin
Ottawa Canada
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-users/attachments/20180509/849e1807/attachment.html>
More information about the Matplotlib-users
mailing list