Reputation: 63
I want to replace the current x-axis label to the label shown below:
labels = ["Oct","Nov","Dec", "Jan", "Feb", "Mar", "April", "May", "June", "July"]
The code I've used to generate the plot is:
df.groupby(pd.Grouper(key='Date', freq='1M')).sum().plot.bar(legend=False)
The output that I got is shown below, here you can see the x-axis have label as dates.
How I can replace those labels with Month names?
Upvotes: 0
Views: 1428
Reputation: 30032
You could have a look at Date formatters. There exists DateFormatter class which accepts a fmt
argument which is a strftime
format string.
Here is a reference of strftime()
and strptime()
format codes.
To format as month abbreviated name, you need to use %b
.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
ax = df.groupby(pd.Grouper(key='Date', freq='1M')).sum().plot.bar(legend=False)
ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt='%b'))
plt.show()
Upvotes: 0
Reputation: 30971
First generate your groupby result:
tbl = df.groupby(pd.Grouper(key='Date', freq='M')).sum()
Then change the index from "full" dates into abbreviated month names:
tbl.set_index(tbl.index.month_name().rename('Month').map(lambda tt: tt[:3]), inplace=True)
And finally draw your figure:
tbl.plot.bar(legend=False);
Note the trailing ;
to prevent from additional display concerning
the type of the created object.
Upvotes: 1