BhishanPoudel
BhishanPoudel

Reputation: 17164

How to change xticks to yearly interval in pandas time series plot

I am very new to pandas, and I have searched many StackOverflow questions similar to this for changing xtick labels yearly, but they all are different did not solve my problem, so I decided to ask my own question.

Here is my question. I have a mock data frame which I want to plot yearly xticks in the x-axis.

import numpy as np
import pandas as pd

df = pd.DataFrame({'date': pd.date_range('1991-01-01','2019-01-01')}).set_index('date')
df['value'] = np.random.randn(len(df))
df.plot()

This gives: Xticks ==> 1995 2000 2005 etc But I want ==> 1991 1992 ... 2019

How to do that?

So far I have tried this:

import matplotlib
import matplotlib
import matplotlib.pyplot as plt

%matplotlib inline

fig,ax = plt.subplots()
df.plot(ax=ax)

ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(base=1))
# ax.xaxis.set_minor_locator(matplotlib.dates.YearLocator(base=1))

# ax.set_xticklabels(list(df.index.time))

This gives just 2005 as xtick and nothing has worked till now.

Links I looked: - Changing xticks in a pandas plot - Python: Change the time on xticks for Pandas Plot - https://matplotlib.org/3.1.1/api/dates_api.html

Upvotes: 3

Views: 11744

Answers (2)

BhishanPoudel
BhishanPoudel

Reputation: 17164

You can try this:

import datetime

# create xticks
 xticks = pd.date_range(datetime.datetime(1990,1,1), datetime.datetime(2020,1,1), freq='YS')

# plot
fig, ax = plt.subplots(figsize=(12,8))
df['value'].plot(ax=ax,xticks=xticks.to_pydatetime())
ax.set_xticklabels([x.strftime('%Y') for x in xticks]); 
plt.xticks(rotation=90);

Complete Example

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime

# data
df = pd.DataFrame({'date': pd.date_range('1991-01-01','2019-01-01')}).set_index('date')
df['value'] = np.random.randn(len(df))

# create xticks
xticks = pd.date_range(datetime.datetime(1990,1,1), datetime.datetime(2020,1,1), freq='YS')

# plot
fig, ax = plt.subplots(figsize=(12,8))
df['value'].plot(ax=ax,xticks=xticks.to_pydatetime())
ax.set_xticklabels([x.strftime('%Y') for x in xticks]);
plt.xticks(rotation=90);
plt.show()

This gives: enter image description here

Upvotes: 4

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339480

You need to use the x_compat=True argument to have pandas choose the units in a way that they are compatible with matplotlib.dates locators and formatters.

df.plot(ax=ax, x_compat=True)

Complete code:

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
df = pd.DataFrame({'date': pd.date_range('1991-01-01','2019-01-01')}).set_index('date')
df['value'] = np.random.randn(len(df))


fig,ax = plt.subplots()
df.plot(ax=ax, x_compat=True)

ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(base=1))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))

plt.show()

enter image description here

Upvotes: 7

Related Questions