0

Plot displaying properly

x=[]
y=[]    
figure = Figure(figsize=(5, 4), dpi=100) 
plot = figure.add_subplot(1, 1, 1)
figure.suptitle(Date, fontsize=12)
plot.plot(x, y, color="blue")
cursor = Cursor(plot,horizOn=True,vertOn=False,color="green",linewidth=2.0)
canvas = FigureCanvasTkAgg(figure, root)                    
canvas.get_tk_widget().grid(column=0, row=3,columnspan=4,pady = 4, padx=4)

cursor = Cursor() takes ax and it seems i cant put plot.axes

Joe_bart
  • 17
  • 3
  • You can bind the canvas and get x, y coordinates using event.x and event.y –  Jun 02 '21 at 09:19
  • `Cursor` is for having a crosshair where your cursor currently is. For having a crosshair to the closest data point from your cursor and displaying the coordinates, you need a mouse event where you get the x/y coordinates of your mouse and then figure out what the closest data point in your graph is to set your vertical/horizontal lines + text. See [this answer](https://stackoverflow.com/questions/44679473/add-cursor-to-matplotlib) for an example. – Reti43 Jun 02 '21 at 09:27

1 Answers1

0

You need to create the Cursor instance after creating the canvas:

canvas = FigureCanvasTkAgg(figure, root)
canvas.get_tk_widget().grid(column=0, row=3,columnspan=4,pady = 4, padx=4)

cursor = Cursor(plot, horizOn=True, vertOn=False, color="green", linewidth=2.0)

Full example code:

import tkinter as tk
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from matplotlib.widgets import Cursor

Date = "2021-06-01"

root = tk.Tk()

x = []
y = []

figure = Figure(figsize=(5, 4), dpi=100)
plot = figure.add_subplot(1, 1, 1)
#print(plot)
figure.suptitle(Date, fontsize=12)
plot.plot(x, y, color="blue")

canvas = FigureCanvasTkAgg(figure, root)
canvas.get_tk_widget().grid(column=0, row=3,columnspan=4,pady = 4, padx=4)

# pack_toolbar=False will make it easier to use a layout manager later on.
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()
toolbar.grid(sticky="ew")

cursor = Cursor(plot, useblit=True, horizOn=True, vertOn=True, color="green", linewidth=2.0)

root.mainloop()

And the output:

enter image description here

acw1668
  • 40,144
  • 5
  • 22
  • 34