通过删除/替换旧值来更新 matplotlib 子图

发布于 2025-01-11 16:07:44 字数 2084 浏览 0 评论 0原文

我编写了一个非常简单的代码来在 matplotlib 子图中绘制散点图。我可以使用 plot() 函数根据 x, y1 的值进行绘图。我想知道我是否通过另一个函数获得了新值,例如 y2 ,如何在图中更新它?我检查了这方面的其他帖子,有一些建议在更新中使用 clear()destroy()delete() ( )功能,但它们都不起作用。我想保留画布和图形的设置,仅用旧值替换新值。

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


class Data:
    def __init__(self):
        self.x = tk.IntVar()


class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(700, 700)
        container = tk.Frame(self)
        container.pack()

        self.data = Data()

        self.frames = {}
        for F in (PageOne, ):
            frame = F(container, self.data)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()


class PageOne(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        self.button1 = tk.Button(self, text="Plot", command=self.plot)
        self.button1.pack()

        self.button2 = tk.Button(self, text="update", command=self.update)
        self.button2.pack()

        self.frame = tk.LabelFrame(self)
        self.frame.pack()

    def plot(self):
        global x
        x = [1,2,3,4,5,6,7,8,9]
        y1 = [1,2,3,4,5,6,7,8,9]

        self.figure = Figure(figsize=(4, 4))
        ax = self.figure.add_subplot(111)
        ax.scatter(x, y1)
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')

        canvas = FigureCanvasTkAgg(self.figure, self.frame)
        canvas.draw()
        canvas.get_tk_widget().pack()
        toolbar = NavigationToolbar2Tk(canvas, self.frame)
        toolbar.pack()
        canvas.get_tk_widget().pack()

    def update(self):
        global x
        self.figure.clear()
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]

app = SampleApp()
app.mainloop()

I have written a very simple code to have a scatter plot in matplotlib subplot. I can plot based on the values for x, y1 with the plot() function. I want to know if I got new values such as y2 through another function, how to update it in on the figure? I checked other posts in this regard and there were some suggestions to use clear(), destroy(), delete() in the update() function but none of them works. I want to keep the settings for the canvas and figure and only replace the new values with the old values.

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


class Data:
    def __init__(self):
        self.x = tk.IntVar()


class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(700, 700)
        container = tk.Frame(self)
        container.pack()

        self.data = Data()

        self.frames = {}
        for F in (PageOne, ):
            frame = F(container, self.data)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()


class PageOne(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        self.button1 = tk.Button(self, text="Plot", command=self.plot)
        self.button1.pack()

        self.button2 = tk.Button(self, text="update", command=self.update)
        self.button2.pack()

        self.frame = tk.LabelFrame(self)
        self.frame.pack()

    def plot(self):
        global x
        x = [1,2,3,4,5,6,7,8,9]
        y1 = [1,2,3,4,5,6,7,8,9]

        self.figure = Figure(figsize=(4, 4))
        ax = self.figure.add_subplot(111)
        ax.scatter(x, y1)
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')

        canvas = FigureCanvasTkAgg(self.figure, self.frame)
        canvas.draw()
        canvas.get_tk_widget().pack()
        toolbar = NavigationToolbar2Tk(canvas, self.frame)
        toolbar.pack()
        canvas.get_tk_widget().pack()

    def update(self):
        global x
        self.figure.clear()
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]

app = SampleApp()
app.mainloop()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

筱果果 2025-01-18 16:07:44

我通过结合我的建议和我在 另一篇文章

这是我的做法,仅修改您的 update 函数。

    def update(self):
        global x
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        x = [1,2,3,4,5,6,7,8,9]
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        ax.scatter(x, y2)
        self.figure.canvas.draw()

以下是我使用 set_data 方法实现的方法。


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


class Data:
    def __init__(self):
        self.x = tk.IntVar()


class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(700, 700)
        container = tk.Frame(self)
        container.pack()

        self.data = Data()

        self.frames = {}
        for F in (PageOne, ):
            frame = F(container, self.data)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()


class PageOne(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        self.button1 = tk.Button(self, text="Plot", command=self.plot)
        self.button1.pack()

        self.button2 = tk.Button(self, text="update", command=self.update)
        self.button2.pack()

        self.frame = tk.LabelFrame(self)
        self.frame.pack()


    def plot(self):
        global x
        x = [1,2,3,4,5,6,7,8,9]
        y1 = [1,2,3,4,5,6,7,8,9]

        self.figure = Figure(figsize=(4, 4))
        ax = self.figure.add_subplot(111)
        l = ax.plot(x, y1, lw=0, marker='o') # Changed here
        self.line1 = l[0] # Changed here
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')

        canvas = FigureCanvasTkAgg(self.figure, self.frame)
        canvas.draw()
        canvas.get_tk_widget().pack()
        toolbar = NavigationToolbar2Tk(canvas, self.frame)
        toolbar.pack()
        canvas.get_tk_widget().pack()

    def update(self):
        global x
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        self.line1.set_data(x, y2) # Changed here
        self.figure.canvas.draw()  # Changed here <-- without this, won't redraw

app = SampleApp()
app.mainloop()

您的代码中有一些奇怪的东西,例如未使用的 global x ,但这是下次的内容。

I got it to work by a combination of what I suggested and something I found in another post.

Here's how I did it, modifying only your update function.

    def update(self):
        global x
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        x = [1,2,3,4,5,6,7,8,9]
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        ax.scatter(x, y2)
        self.figure.canvas.draw()

Here's how I did it using the set_data method.


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


class Data:
    def __init__(self):
        self.x = tk.IntVar()


class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(700, 700)
        container = tk.Frame(self)
        container.pack()

        self.data = Data()

        self.frames = {}
        for F in (PageOne, ):
            frame = F(container, self.data)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()


class PageOne(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        self.button1 = tk.Button(self, text="Plot", command=self.plot)
        self.button1.pack()

        self.button2 = tk.Button(self, text="update", command=self.update)
        self.button2.pack()

        self.frame = tk.LabelFrame(self)
        self.frame.pack()


    def plot(self):
        global x
        x = [1,2,3,4,5,6,7,8,9]
        y1 = [1,2,3,4,5,6,7,8,9]

        self.figure = Figure(figsize=(4, 4))
        ax = self.figure.add_subplot(111)
        l = ax.plot(x, y1, lw=0, marker='o') # Changed here
        self.line1 = l[0] # Changed here
        ax.set_title('Test')
        ax.set_xlabel('x')
        ax.set_ylabel('y')

        canvas = FigureCanvasTkAgg(self.figure, self.frame)
        canvas.draw()
        canvas.get_tk_widget().pack()
        toolbar = NavigationToolbar2Tk(canvas, self.frame)
        toolbar.pack()
        canvas.get_tk_widget().pack()

    def update(self):
        global x
        y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        self.line1.set_data(x, y2) # Changed here
        self.figure.canvas.draw()  # Changed here <-- without this, won't redraw

app = SampleApp()
app.mainloop()

There's a few weird things in your code like global x that's unused, but that's stuff for another time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文