In the following example when I hover the cursor over the image, as well as the text I want displaying in the bottom left corner, there is also the gray scale value of the corresponding pixel. Is there a way to suppress this information (or format it)?
import numpy as np
import matplotlib.pyplot as plt
class test():
def __init__(self):
fig=plt.figure()
ax=fig.add_subplot(111)
ax.imshow(np.random.rand(20,20))
def format_coord(x,y):
return "text_string_made_from(x,y)"
ax.format_coord=format_coord
fig.canvas.draw()
One can use the ax.format_coord to change the x and y coordinate part of the statusbar message

by replacing the method with a custom one,
def format_coord(x,y):
return "text_string_made_from({:.2f},{:.2f})".format(x,y)
ax.format_coord=format_coord

Unfortunately the data values in square brackets are not given by the ax.format_coord, but instead they are set by a mouse_move method of the navigation toolbar.
What makes it worse is that the mouse_move is a class method which calls another method .set_message to actually display the message. Since the toolbar is backend dependend, we cannot simply replace it.
Instead we need to monkey patch it, such that the toolbar instance is given as first argument to the class method. This makes the solution a bit cumbersome.
In the below we have a function mouse_move, which sets a message to display. This is the usual x&y coordinates from the format_coord. It takes the instance of the toolbar as argument and would then call the toolbar's .set_message method. We then use another function mouse_move_patch, which calls the mouse_move function with the toolbar instance as argument. The mouse_move_patch function is connected to the 'motion_notify_event'.
import numpy as np
import matplotlib.pyplot as plt
def mouse_move(self,event):
if event.inaxes and event.inaxes.get_navigate():
s = event.inaxes.format_coord(event.xdata, event.ydata)
self.set_message(s)
class test():
def __init__(self):
fig=plt.figure()
ax=fig.add_subplot(111)
ax.imshow(np.random.rand(20,20))
def format_coord(x,y):
return "text_string_made_from({:.2f},{:.2f})".format(x,y)
ax.format_coord=format_coord
mouse_move_patch = lambda arg: mouse_move(fig.canvas.toolbar, arg)
fig.canvas.toolbar._idDrag = fig.canvas.mpl_connect(
'motion_notify_event', mouse_move_patch)
t = test()
plt.show()
This will result in the desired ommitance of the data values in the status bar message

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