Maybe
Maybe

Reputation: 2279

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 enter image description here

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

Many thanks.

Upvotes: 6

Views: 6814

Answers (1)

rrcal
rrcal

Reputation: 3752

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

enter image description here

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

enter image description here

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

enter image description here

Upvotes: 4

Related Questions