Reputation: 5331
This code will produce the figure below:
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()
I wish to indicate when the two events marked by a star happened.
How do force pyplot to draw a tick under the locations of the two stars?
I figured out that I need to use custom locator. But how exactly? It looks like it will produce evenly spaced ruler only.
rule = rrulewrapper(???)
loc = RRuleLocator(rule)
Upvotes: 0
Views: 132
Reputation: 339775
If you have a defined location of the ticks, you can use the 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()
I made the special ticklabels red, because they overlap the existing ticklabels. I guess you need to decide for yourself how you want to have it appear in the end.
Upvotes: 1