使用matplotlib按时间序列自定义日期范围(x轴)

KGo*_*KGo 2 python time-series matplotlib

我绘制时间序列的代码是这样的:

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers

    fig.autofmt_xdate()
    plt.grid(True)
    plt.show()
Run Code Online (Sandbox Code Playgroud)

我有几千个数据点,所以matplotlib创建3个月的x轴范围.这就是我现在的时间序列:

在此输入图像描述

但是,我想要每周/每两周播放一次.如何更改matplotlib计算x轴日期范围的方式,由于我有近1年的数据,如何确保所有数据都能很好地适用于单个图表?

sod*_*odd 8

要更改x轴上刻度线的频率,必须设置其定位器.

要为每周的每个星期一打勾,您可以使用matplotlib模块WeekdayLocator提供的dates.

(未经测试的代码):

from matplotlib.dates import WeekdayLocator

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers        

    fig.autofmt_xdate()

    # For tickmarks and ticklabels every week
    ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO))

    # For tickmarks and ticklabels every other week
    #ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=2))

    plt.grid(True)
    plt.show()
Run Code Online (Sandbox Code Playgroud)

当仅使用一个图时,这可能在x轴上有点拥挤,因为这会产生大约52个刻度.

一个可能的解决方法是每隔n周(例如每隔4周)使用滴答标记,并且每周只有滴答标记(即没有滴答标记):

from matplotlib.dates import WeekdayLocator

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers        

    fig.autofmt_xdate()

    # For tickmarks and ticklabels every fourth week
    ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=4))

    # For tickmarks (no ticklabel) every week
    ax.xaxis.set_minor_locator(WeekdayLocator(byweekday=MO))

    # Grid for both major and minor ticks
    plt.grid(True, which='both')
    plt.show()
Run Code Online (Sandbox Code Playgroud)