Python Forum

Full Version: Update matplotlib plot correctly
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Evening,

I want to insert a data point externally into an existing plot (f(x) = x, g(x) = x**2). To do this, the x and y coordinates can be entered in entry fields. The user can then press a button to insert the point.

Assuming a data point (x1, y1) is inserted and the user trys to enter a new data point (x2,y2). In this case the GUI should only display the curves (f(x), g(x)) and the point (x2, y2). The last point (x1,y1) should be deleted.


My solution only partially works: Additional points (x,y) can be created, but the old ones are not deleted...

Does any of you know an approach to solve the problem described above.

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import numpy as np

fig = Figure(figsize = (9, 6), facecolor = "white")

axis = fig.add_subplot(111)
x_values = np.array([1,2,3,4,5,6,7])
axis.plot(x_values, x_values, "-r")
axis.plot(x_values, x_values ** 2, "--g")
axis.grid()

root = tk.Tk()

Label(root, text = "x =" ).grid(row = 0, column = 0)
Label(root, text = "y =" ).grid(row = 1, column = 0)

x = DoubleVar()
y = DoubleVar()

x_entry = Entry(root, textvariable = x).grid(row = 0, column = 1)
y_entry = Entry(root, textvariable = y).grid(row = 1, column = 1)

def plotgraphs():
    axis.plot(x.get(), y.get(), "ko")
    
    canvas = FigureCanvasTkAgg(fig, master = root)
    canvas._tkcanvas.grid(row = 2, column = 1)

Button(root, text = "New Graphs", command = plotgraphs).grid(row = 0, column = 2)

canvas = FigureCanvasTkAgg(fig, master = root)
canvas._tkcanvas.grid(row = 2, column = 1)

root.mainloop()