简体   繁体   中英

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.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(np.arange(1000))
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

I get the following figure, without x-ticks 在此处输入图片说明

I'm wondering why all x-ticks disappeared? I wrote the above code with reference to this implementation

Many thanks.

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:

  1. Transform your date using pd.to_datetime
  2. Set it to your dataframe index.
  3. 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 in range(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'))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM