簡體   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