gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:24:04 26 4
gpt4 key购买 nike

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

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 轴范围。这就是我的时间序列现在的样子:

enter image description here

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

最佳答案

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

要为每周的每个星期一设置刻度线,您可以使用 WeekdayLocatordates 提供matplotlib 模块。

(未经测试的代码):

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

当只使用一个图时,这可能会在 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()

关于python - 使用 matplotlib 的时间序列中的自定义日期范围(x 轴),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17987468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com