Cannot configure x-axis of DateFormat in pandas table

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

However, I cannot do the same for the data.plot(kind='bar') histogram data.plot(kind='bar') . And the chart will not appear. Is there a way to change the data format for the pandas histogram? I know that I can create a chart using the plt.bar method, but I need to use pandas complex histogram for more complex 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')) 
+8
matplotlib pandas
source share
2 answers

Since Pandas just uses matplotlib, you can, of course, create an identical (stacked) barchart with matplotlib. There is no reason why you can use Pandas for this.

In this case, he is not going to help. Matplotlib bar() changes the x values ​​from dates to float, so DateFormatter no longer works. You can check xticks with ax.get_xticks() .

I don’t see how you can create xticks dates, but you can override xticklabels yourself:

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

If you grouped your data using groupby , then you can do the same 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]) 

The mine was summed up and grouped by month, so the index tuple was only (2009,4) . Obviously, if you have more aspects for your tuple (i.e. Day, hour), you can add them to the datetime function

0
source share

All Articles