我绘制时间序列的代码是:
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年的数据,如何确保所有数据都能很好地适用于单个图表?
答案 0 :(得分:7)
要更改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()
当仅使用一个绘图时,这可能会在x轴上有点拥挤,因为这会产生大约52个刻度。
一个可能的解决方法是每周 n - 星期(例如每4周)都有一个ticklabel,并且每周只有tickmarks(即没有ticklabels):
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()