I'm plotting a time-series with MatplotLib. The time series values, x-axis, have the resolution '%d/%m/%y %H:%M', but only month and year are indicated in the mouse over.
My question is how can one override the default and set what datetime items that should be shown during mouse over?
My preference is to show at least day, month, and year
.....................................................................
For example, this is a screenshot where I did a mouse-over for one of the points:

As you can see the (bottom LHS corner) x value gives a date which indicated only month and year.
When zoomed in, day, month and year are shown:

The values that are shown on mouse-over are controlled by the ax.format_coord method, which is meant to be monkey-patched by a user-supplied method when customization is needed.
For example:
import matplotlib.pyplot as plt
def formatter(x, y):
return '{:0.0f} rainbows, {:0.0f} unicorns'.format(10*x, 10*y)
fig, ax = plt.subplots()
ax.format_coord = formatter
plt.show()
There are also the ax.format_xdata and ax.format_ydata which the default ax.format_coord calls, to allow easier customization of only the x or y components.
For example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.format_xdata = '{:0.1f}meters'.format
plt.show()
Note that I passed in the string's format method, but it could have just as easily been a lambda or any arbitrary method that expects a single numeric argument.
By default, format_xdata and format_ydata use the axis's major tick formatter, which is why you're getting day-level resolution for your date axis.
However, you'll also need to convert matplotlib's internal numeric date format back to a "proper" datetime object. Therefore, you can control your formatting similar to the following:
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots()
ax.xaxis_date()
ax.set_xlim(dt.datetime(2015, 1, 1), dt.datetime(2015, 6, 1))
ax.format_xdata = lambda d: mdates.num2date(d).strftime('%d/%m/%y %H:%M')
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With