简体   繁体   中英

How to set the step size of dates in x-axis using matplotlib?

I am using matplotlib to draw a plot between a value and its corresponding date.

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

levels = pd.read_csv(r'F:levels.csv', usecols=[0,1], parse_dates=[0])
levels.head(3)

Date        Level (m)
1972-04-06  Nan
1972-04-07  309
1972-04-08  311

years = mdates.YearLocator()
years_fmt = mdates.DateFormatter('%Y')

ig,ax = plt.subplots(figsize=(12,7))

ax.plot(levels['Date'],levels['Level (m)'], color ='green')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

plt.xlabel("Year")
plt.ylabel("Level in meters")
plt.xticks(rotation=45)
plt.legend()

The output plot looks like: 在此处输入图像描述

Expected Output:

Here, I want the time step of x-axis to be 5 years. ie, I want only the years 1970, 1975, 1980, 1985, 1990, 2000... years on x-axis.

Just use years = YearLocator(base = 5) , as in the following example (with random data):

dates = pd.date_range("1960-01-01", "2020-06-30", freq="1d")
dates = sorted(np.random.choice(dates, 100))

years = matplotlib.dates.YearLocator(base = 5)
years_fmt = matplotlib.dates.DateFormatter('%Y')

levels = pd.DataFrame({"Date": dates, 'Level (m)': random.rand(len(dates)) * 1000})

ig,ax = plt.subplots(figsize=(12,7))

ax.plot(levels['Date'],levels['Level (m)'], color ='green')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

plt.xlabel("Year")
plt.ylabel("Level in meters")
plt.xticks(rotation=45)
plt.legend()

The output is:

在此处输入图像描述

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