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()

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.
python date matplotlib pandas
SpicyClubSauce
source share