Matplotlib mouse cursor coordinates not shown for empty tick labels

Viewed 640

In matplotlib, interactive plot windows show the mouse cursor plot coordinates in the bottom left corner.

import matplotlib.pyplot as plt

plt.ion()
ax = plt.gca()

However, assume I want to hide (not necessarily remove) the tick labels on the y-axis, e.g. via

ax.set_yticklabels([])

The tick labels are gone, but the mouse cursor plot coordinates are not displayed anymore for the y-axis. Another way to hide the y-axis would be

ax.tick_params(labelleft=False)

This preserves mouse cursor coordinates. How comes the empty tick label list "destroys" the coordinate information as well? I assumed the expected behavior would be that a tick label does not change the underlying plot coordinates, whatever specifies them (imshow's extent, the x-arrays of plt.plot etc.).

1 Answers

The coordinate formatter on the toolbar is determined by the current Axes formatters. By default, before you set the yticklabels, that is a ticker.ScalarFormatter instance. When you run ax.set_yticklabels([]), the formatter is set to a ticker.FixedFormatter instance, which in this case is obviously customised to return an empty string for any input value (so that you don't get any tick labels).

You can restore the toolbar's original functionality by setting ax.format_coord to a function which formats your coordinates however you want. For example:

ax.format_coord = lambda x, y: 'x={:g}, y={:g}'.format(x, y)

In a minimal example:

import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots()
ax.set_yticklabels([])
ax.format_coord = lambda x, y: 'x={:g}, y={:g}'.format(x, y)

enter image description here

Related