所以我正在研究與線性回歸圖相關的東西。到目前為止,我已經創建了這個簡單的程式,它可以創建一個圖表,允許您添加點、隨機生成 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()
此外,任何關于如何改進我的程式的建議都將不勝感激:)
uj5u.com熱心網友回復:
在繪制其他任何內容之前,您應該正確清除情節。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438520.html
標籤:Python matplotlib
上一篇:matplotlib/seaborn中我的y軸外的框
下一篇:使用Python多次提取輪廓
