How To Set X-ticks To Months With `set_major_locator`?
I am trying to use the following code to set the x-ticks to [Jan., Feb., ...] import matplotlib.pyplot as plt from matplotlib.dates import MonthLocator, DateFormatter fig = plt.fig
Solution 1:
It is not very clear the type of data you currently have. But below are my suggestions for plotting the month on the x-axis:
- Transform your date using
pd.to_datetime
- Set it to your dataframe index.
- Call explicitly the
plt.set_xticks()
method
Below one example with re-created data:
from datetime import datetime as dt
from datetime import timedelta
### create sample data
your_df = pd.DataFrame()
your_df['vals'] = np.arange(1000)
## make sure your datetime is considered as such by pandas
your_df['date'] = pd.to_datetime([dt.today()+timedelta(days=x) for x inrange(1000)])
your_df= your_df.set_index('date') ## set it as index### plot it
fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(your_df['vals'])
plt.xticks(rotation='vertical')
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))
Note that if you do not want every month plotted, you can let matplotlib handle that for you, by removing the major locator.
fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(your_df['vals'])
plt.xticks(rotation='vertical')
# ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))
Added Went into the link provided, and you do have a DATE
field in the dataset used (boulder-precip.csv
). You can actually follow the same procedure and have it plotted on a monthly-basis:
df = pd.read_csv('boulder-precip.csv')
df['DATE'] = pd.to_datetime(df['DATE'])
df = df.set_index('DATE')
fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(df['PRECIP'])
plt.xticks(rotation='vertical')
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))
Post a Comment for "How To Set X-ticks To Months With `set_major_locator`?"