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

Python 使用matplotlib的时间序列中的自定义日期范围(x轴),python,matplotlib,time-series,Python,Matplotlib,Time Series,我绘制时间序列的代码如下: 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() 我有几千个数据点,因此matplotlib创建了3个月的x轴范围。这就是我的时间序列现在的样子

我绘制时间序列的代码如下:

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()
我有几千个数据点,因此matplotlib创建了3个月的x轴范围。这就是我的时间序列现在的样子:


但是,我想要一个每周/每两周的系列。如何更改matplotlib计算x轴日期范围的方式,以及由于我有将近1年的数据,如何确保所有数据都能很好地放在一张图表中?

要更改x轴上记号的频率,必须设置其定位器

要为每周的每个星期一设置记号,可以使用matplotlib模块提供的

(未测试代码):

当仅使用一个绘图时,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()

ax.set\xlim([min\u time,max\u time])
这样简单的东西会起作用吗?还是需要更自动化的东西?这会限制最小值和最大值。我想要的是更“放大”的图形。因此,我希望间隔1周或2周,而不是3个月。如果我在跟踪您,您希望将数据读入pandas数据帧,然后重新采样:连同
ax.xaxis.set\u major\u格式化程序(DateFormatter(“%Y-%m-%d”)
,这就像charm!
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()