【问题标题】:How to set the step size of dates in x-axis using matplotlib?如何使用matplotlib设置x轴日期的步长?
【发布时间】:2020-07-13 05:47:33
【问题描述】:

我正在使用 matplotlib 绘制一个值与其对应日期之间的图。

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

输出图如下所示:

预期输出:

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    只需使用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()
    

    输出是:

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多