Why does my date axis formatting break when building with Pandas' built-in plot calls and not through Matplotlib?

I collect aggregated data in Python using Pandas and Matlplotlib. My axis setup commands do not work as a function from which of two similar functions I call to make line graphs. A working case is, for example:

import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates def format_x_date_month_day(ax): days = mdates.DayLocator() months = mdates.MonthLocator() # every month dayFmt = mdates.DateFormatter('%D') monthFmt = mdates.DateFormatter('%Y-%m') ax.figure.autofmt_xdate() ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthFmt) ax.xaxis.set_minor_locator(days) span_days = 90 start = pd.to_datetime("1-1-2012") idx = pd.date_range(start, periods=span_days).tolist() df=pd.DataFrame(index=idx, data={'A':np.random.random(span_days), 'B':np.random.random(span_days)}) plt.close('all') fig, ax = plt.subplots(1) ax.bar(df.index, df.A) # loop over columns here to do stacked plot format_x_date_month_day(ax) plt.show() 

(see matplotlib.org , for example, a loop to create a line-by-line graph.) This gives us

String Bar, called from Matplotlib, formatting the axis using <code> mdates </code>

Another approach, which should work and be much simpler, is to use df.plot.bar(ax=ax, stacked=True) , however it does not allow formatting the date axis with mdates :

 plt.close('all') fig, ax = plt.subplots(1) df.plot.bar(ax=ax, stacked=True) format_x_date_month_day(ax) plt.show() 

Stacked bar with broken x-axis label

How can mdates and ax.figure.autofmt_xdate() be made to play well with df.plot.bar ?

0
python matplotlib pandas
Dec 25 '17 at 1:10
source share

No one has answered this question yet.

See similar questions:

36
Pandas bar chart size changes date format

or similar:

303
When to use cla (), clf () or close () to clear a plot in matplotlib?
228
Matplotlib Charts: Removing Axis, Legends and Spaces
194
Hiding axis text in matplotlib plots
128
Why is my xlabel cut off on my matplotlib patch?
13
Plot of pandas dates in matplotlib
four
Using matplotlib * without * TCL
3
Problem with xticklabels when saving shape with matplotlib
2
how to overlay a panda plot, matplotlib chart and axis
0
Pandas Chart
-one
Specify dates on x-axis plot from pandas data frame



All Articles