I have a Matplotlib
figure in Tkinter
canvas with a NavigationToolbar2Tk
below.
When the mouse is on the canvas area, the toolbar automatically displays the (x, y)
coordinates on the right hand side of the toolbar.
How can I change the number of digits displayed in the(x, y)
coordinates ?
MWE
from tkinter import Frame, Tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
window_main = Tk()
matplotlib.use("TkAgg") # Set matplotlib backend
fig = plt.Figure()
# Create canvas to hold figure
canvas = FigureCanvasTkAgg(fig, window_main)
canvas.get_tk_widget().grid(column=0, row=0)
canvas.draw()
# Create toolbar
toolbar_frame = Frame(window_main)
toolbar_frame.grid(column=0, row=1)
toolbar = NavigationToolbar2Tk(canvas, toolbar_frame)
ax = fig.add_subplot(111)
data_x = [1,2,3]
data_y = [2.5,4,1.2]
ax.plot(data_x,data_y)
fig.canvas.draw_idle()
window_main.mainloop()
You can override ax.format_coord
with a custom formatter function as described in this documentation. Here's a working example:
from tkinter import Frame, Tk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
def custom_format_coord(x: float, y: float) -> str:
return f'x is {x:1.5f}, y is {y:1.5f}' # format however you want!
window_main = Tk()
matplotlib.use("TkAgg") # Set matplotlib backend
fig = plt.Figure()
# Create canvas to hold figure
canvas = FigureCanvasTkAgg(fig, window_main)
canvas.get_tk_widget().grid(column=0, row=0)
canvas.draw()
# Create toolbar
toolbar_frame = Frame(window_main)
toolbar_frame.grid(column=0, row=1)
toolbar = NavigationToolbar2Tk(canvas, toolbar_frame)
ax = fig.add_subplot(111)
data_x = [1,2,3]
data_y = [2.5,4,1.2]
ax.plot(data_x,data_y)
# use the custom coordinate formatter to override ax.format_coord
ax.format_coord = custom_format_coord
fig.canvas.draw_idle()
window_main.mainloop()
Your custom coordinate formatter function will need to accept two float
values, x
and y
, as those are passed in automatically.