8
votes

I wish to plot a pandas time-series object data with matplotlib. For a simple line chart data.plot(), I was able to successfully change the x-axis date format with ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d %H:%M:%S')).

However, I am not able to do the same for a bar chart data.plot(kind='bar'). And the chart wouldn't appear. Is there a way to change data format for pandas bar chart? I know I can create a chart with plt.bar method, but I need to use pandas stacked bar chart for more complicated data.

import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import pandas as pd
import datetime as dt
import time

n=20
duration=1000
now=time.mktime(time.localtime())
timestamps=np.linspace(now,now+duration,n)
dates=[dt.datetime.fromtimestamp(ts) for ts in timestamps]
values=np.sin((timestamps-now)/duration*2*np.pi)
data=pd.Series(values, index=dates)

fig=figure(figsize(5,5))
ax=fig.add_subplot(111)
data.plot(kind='bar')
ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d %H:%M:%S'))
2

2 Answers

17
votes

Since Pandas simply uses matplotlib you can of course create an identical (stacked) barchart with matplotlib. There is not reason why you can only use Pandas for that.

Its not going to help in this case though. Matplotlib's bar() changes the xvalues from dates to floats, therefore a DateFormatter doesnt work anymore. You can check the xticks with ax.get_xticks().

I dont see how you can make the xticks dates, but you can override the xticklabels yourself:

ax.set_xticklabels([dt.strftime('%Y-%m-%d %H:%M:%S') for dt in data.index.to_pydatetime()])
0
votes

If you have grouped your data using groupby then you can do the same thing as the answer above using:

new_ticks = []
for dt in data.index:
    new_ticks.append(datetime.datetime(dt[0],dt[1],1))
ax.set_xticklabels([dt.strftime('%Y-%m') for dt in new_ticks])

Mine was summed and grouped by month so the index tuple was only (2009,4) for example. Obviously, if you have more aspects to your tuple (i.e. day, hour) then you would add those to the datetime function