我撰寫了一個非常簡單的代碼來繪制散點圖。我想知道如何y-axis通過 a引入新的second function并更新圖形來替換圖形。在這個例子中,我可以根據x, y1. 我想知道我是否y2通過另一個函式獲得了新值,如何更新圖形?
from tkinter import *
import matplotlib.pyplot as plt
root = Tk()
def plot():
x = [1,2,3,4,5,6,7,8,9]
y1 = [1,2,3,4,5,6,7,8,1]
plt.scatter(x, y1)
plt.title('Test')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def update():
y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]
my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()
my_button2 = Button(root, text="update", command=update)
my_button2.pack()
root.mainloop()
uj5u.com熱心網友回復:
使 Y 值成為全域變數。您還可以x自動適應這個長度,而不是硬編碼 9 個元素。
from tkinter import *
import matplotlib.pyplot as plt
root = Tk()
y_values = [1,2,3,4,5,6,7,8,1]
def plot():
x = list(range(1, len(y_values) 1))
plt.scatter(x, y_values)
plt.title('Test')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def update():
global y_values
y_values = [1, 2, 3, 4, 5, 4, 3, 2, 1]
my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()
my_button2 = Button(root, text="update", command=update)
my_button2.pack()
root.mainloop()
uj5u.com熱心網友回復:
您需要使用全域y串列。該plot()函式讀取該全域變數,該update()函式更新該全域變數(然后plot()在使用 清除圖形后呼叫plt.clf()):
from tkinter import *
import matplotlib.pyplot as plt
root = Tk()
x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,1]
def plot():
# if you want it to be reversible, add :
# global y
# y = [1,2,3,4,5,6,7,8,1]
# plt.clf()
plt.scatter(x, y)
plt.title('Test')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def update():
global y
y = [1, 2, 3, 4, 5, 4, 3, 2, 1]
plt.clf()
plot()
my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()
my_button2 = Button(root, text="update", command=update)
my_button2.pack()
root.mainloop()
uj5u.com熱心網友回復:
如果將資料移動到引數中,則可以呼叫該函式兩次,這將在第一個視窗關閉后繪制新圖形:
x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,1]
def plot(x, y):
plt.scatter(x, y)
plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('ScatterPlot_01.png')
plt.show()
plot(x, y)
y2 = [1,2,3,4,5,4,3,2,1]
plot(x, y2)
如果你想有不同的標題或保存到不同的.png,你可以進一步添加引數plot():
title = 'Nuage de points avec Matplotlib part2'
filename = 'ScatterPlot_02.png'
def plot(x, y, title, filename):
plt.scatter(x, y)
plt.title(title)
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(filename )
plt.show()
plot(x, y2, title, filename)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437489.html
