簡體   English   中英

正確更新 matplotlib plot - tkinter

[英]Update matplotlib plot correctly - tkinter

晚上,

我想將一個數據點從外部插入現有的 plot (f(x) = x, g(x) = x**2)。 為此,可以在輸入字段中輸入 x 和 y 坐標。 然后用戶可以按下按鈕來插入該點。

假設插入了一個數據點 (x1, y1),並且用戶嘗試輸入一個新的數據點 (x2,y2)。 在這種情況下,GUI 應該只顯示曲線 (f(x), g(x)) 和點 (x2, y2)。 最后一點 (x1,y1) 應該被刪除。

我的解決方案僅部分有效:可以創建附加點 (x,y),但不會刪除舊點...

你們中有人知道解決上述問題的方法嗎?

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()

您需要刪除現有點以獲得所需的行為。 下面會做 - 你在找什么。 我確實增強了一點。

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

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", label = 'f(X) = x')
axis.plot(x_values, x_values ** 2, "--g", label = 'f(x) = x\N{SUPERSCRIPT TWO}')
axis.grid()
axis.legend()
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():
    if (len(axis.lines)) == 3: # Count existing plotted lines and delete if already existing
        del (axis.lines[2])
        axis.plot(x.get(), y.get(), "ko", label = 'Input point')
    else:
        axis.plot(x.get(), y.get(), "ko", label = 'Input point')
    axis.legend()
    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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM