重置图形问题(matplotlib)

Resetting graph issues (matplotlib)

所以我正在研究与线性回归图相关的东西。到目前为止,我已经创建了这个创建图形的简单程序,允许您添加点、随机生成 20 个点和一个重置按钮。当我生成随机图时,重置按钮工作正常。也就是说,它将图形重置为空。但是,如果我添加 3 个点 (3,4)、(6,7)、(1,2),然后按下重置按钮,它只会删除我绘制的最新点(在本例中为(1,2) )).有人可以帮我吗?

from tkinter import *
import matplotlib.pyplot as plt
import PIL
import random

points = [[],[]]

screen = Tk()
screen.title("Linear Regression")
screen.geometry("875x900")
graph = None

def point():
    global graph
    points[0].append(int(x_coord.get()))
    points[1].append(int(y_coord.get()))
    x_coord.delete(0, "end")
    y_coord.delete(0, "end")
    graph = plt.scatter(points[0], points[1], color="red")
    plt.savefig("current_graph.png") #640 x 480
    create_image("current_graph.png", 0, -20)

def gen_points():
    points[0] = [i for i in range(1,21)]
    points[1] = [random.randint(1,20)for i in range(20)]
    graph = plt.scatter(points[0], points[1], color="red")
    plt.savefig("current_graph.png") #640 x 480
    create_image("current_graph.png", 0, -20)
    graph.remove()
    points[0] = []
    points[1] = []

def create_image(image_file, posx, posy):
    global graph_image
    image_object = PIL.Image.open(image_file)
    canvas = Canvas(screen, width = image_object.size[0], height = image_object.size[1])
    canvas.place(x = posx, y = posy)
    graph_image = PIL.ImageTk.PhotoImage(image_object)
    canvas.create_image(0, 0, anchor=NW, image = graph_image)

def reset_graph():
    global graph
    print(points)
    if graph != None:
        graph.remove()
        graph = None
    points[0] = []
    points[1] = []
    plt.scatter(points[0], points[1], color="red")
    plt.savefig("current_graph.png") #640 x 480
    create_image("current_graph.png", 0, -20)


plt.scatter(points[0], points[1], color="red")
plt.savefig("current_graph.png") #640 x 480
create_image("current_graph.png", 0, -20)

x_label = Label(screen, text="X:")
x_label.place(x = 640, y = 5)
x_coord = Entry(screen, width = 10)
x_coord.place(x=655, y=5)

y_label = Label(screen, text="Y:")
y_label.place(x = 720, y = 5)
y_coord = Entry(screen, width = 10)
y_coord.place(x=735, y=5)

random_gen = Button(screen, text = "Generate Random Points", command = gen_points)
random_gen.place(x = 655, y = 30)

reset_button = Button(screen, text = "Reset", command = reset_graph)
reset_button.place(x = 805, y = 30)

add_point = Button(screen, text = "Add Point", command = point)
add_point.place(x=805, y = 0)


screen.mainloop()

还有任何关于如何改进我的程序的建议将不胜感激:)

你应该在绘制其他任何东西之前适当地清除绘图。
Matplotlib 有 clf 方法。

只需将您的 reset_graph 函数更改为:

def reset_graph():
    global graph
    print(points)
    if graph != None:
        graph.remove()
        graph = None
    points[0] = []
    points[1] = []
    # Clear the current figure
    plt.clf()
    plt.scatter(points[0], points[1], color="red")
    plt.savefig("current_graph.png") #640 x 480
    create_image("current_graph.png", 0, -20)