要更改 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 周)有一个刻度标签,并且每周只有刻度标记(即没有刻度标签):
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()