Matplotlib DateFormatter for axis label not working

I'm trying to format date stamps on the abscissa so that only the year and month are displayed in it. From what I found on the Internet, I should use mdates.DateFormatter , but it does not take effect with my current code, as it is. Does anyone see where the problem is? (dates are the data pyramid index)

 import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd fig = plt.figure(figsize = (10,6)) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) basicDF['some_column'].plot(ax=ax, kind='bar', rot=75) ax.xaxis_date() 

enter image description here

Playable script code:

 import numpy as np import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd rng = pd.date_range('1/1/2014', periods=20, freq='m') blah = pd.DataFrame(data = np.random.randn(len(rng)), index=rng) fig = plt.figure(figsize = (10,6)) ax = fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) blah.plot(ax=ax, kind='bar') ax.xaxis_date() 

Until now, I can’t find only a year and a month.

If I set the format after .plot, we get an error similar to this:

ValueError: DateFormatter detected a value of x = 0, which is an invalid date. This usually happens because you did not tell the axis what it is plotting on the date graph, for example, using x.xaxis_date() .

The same thing if I put it before ax.xaxis_date () or after.

+15
python date matplotlib pandas
source share
2 answers

Pandas just don't work well with custom date and time formats.

You just need to use raw matplotlib in such cases.

 import numpy import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas N = 20 numpy.random.seed(N) dates = pandas.date_range('1/1/2014', periods=N, freq='m') df = pandas.DataFrame( data=numpy.random.randn(N), index=dates, columns=['A'] ) fig, ax = plt.subplots(figsize=(10, 6)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) ax.bar(df.index, df['A'], width=25, align='center') 

And it gives me:

enter image description here

+15
source share

The accepted answer states that "pandas will not work well with custom date and time formats," but you can use the pandas to_datetime() function to use the existing date and time series in the data frame:

 import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import pandas as pd rng = pd.date_range('1/1/2014', periods=20, freq='m') blah = pd.DataFrame(data = np.random.randn(len(rng)), index=pd.to_datetime(rng)) fig, ax = plt.subplots() ax.xaxis.set_major_formatter(DateFormatter('%m-%Y')) ax.bar(blah.index, blah[0], width=25, align='center') 

As a result:

a bar graph with the dates formatted as described

You can see the various formats available here .

+3
source share

All Articles