繁体   English   中英

如何使用 matplotlib 设置 x 轴日期的步长?

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

我正在使用 matplotlib 在值与其对应日期之间绘制 plot 。

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

output plot 看起来像: 在此处输入图像描述

预期 Output:

在这里,我希望 x 轴的时间步长为 5 年。 即,我只想要 x 轴上的 1970、1975、1980、1985、1990、2000... 年。

只需使用years = YearLocator(base = 5) ,如下例所示(使用随机数据):

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

output 是:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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