Matplotlib 使用绘图日期时强制在特定日期显示刻度

Matplotlib 使用绘图日期时强制在特定日期显示刻度,matplotlib,Matplotlib,此代码将生成下图: import math import matplotlib.pyplot as plt from matplotlib.dates import (YEARLY,HOURLY, DateFormatter, drange) import datetime date1 = datetime.datetime(1952, 1, 1, 1, 1, 1) date2 = datetime.datetime(1952, 1

此代码将生成下图:

import math
import matplotlib.pyplot as plt
from matplotlib.dates import (YEARLY,HOURLY, DateFormatter,
                              drange)
import datetime


date1 = datetime.datetime(1952, 1, 1, 1, 1, 1)
date2 = datetime.datetime(1952, 1, 1, 23, 59, 59)
delta = datetime.timedelta(minutes= 10)

dates = drange(date1, date2, delta)
y = [math.sin(x/10.0) for x,_ in enumerate(dates)]

fig, ax = plt.subplots()

plt.plot_date(dates, y)

plt.plot_date([dates[15],dates[121]], [y[15], y[121]], marker="*", c="yellow", markersize=20)

ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
ax.xaxis.set_tick_params(rotation=45, labelsize=10)

fig.autofmt_xdate()

plt.show()

我想指出这两个以星星为标志的事件是什么时候发生的

如何强制pyplot在两颗星的位置下画一个记号

我发现我需要使用自定义定位器。但具体如何?看起来它只能生成等距标尺

rule = rrulewrapper(???)  
loc = RRuleLocator(rule)

如果已经定义了记号的位置,则可以使用
FixedLocator

import math
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, drange
from matplotlib.ticker import FixedLocator
import datetime


date1 = datetime.datetime(1952, 1, 1, 1, 1, 1)
date2 = datetime.datetime(1952, 1, 1, 23, 59, 59)
delta = datetime.timedelta(minutes= 10)

dates = drange(date1, date2, delta)
y = [math.sin(x/10.0) for x,_ in enumerate(dates)]

fig, ax = plt.subplots()

plt.plot_date(dates, y)

events, = plt.plot_date([dates[15],dates[121]], [y[15], y[121]], 
                   marker="*", c="r", markersize=20, ls="")

ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
ax.xaxis.set_tick_params(which="major", rotation=30, labelsize=9)

ax.xaxis.set_minor_locator(FixedLocator(events.get_xdata()))
ax.xaxis.set_minor_formatter(DateFormatter('%H:%M:%S'))
ax.xaxis.set_tick_params(which="minor", rotation=30, labelsize=10, labelcolor="r")

plt.setp(ax.get_xticklabels(which="both"), ha="right")
plt.show()

我将特殊的标签标记为红色,因为它们与现有的标签重叠。我想你需要自己决定你到底想让它怎么出现