Home > Back-end >  Updating a value in a function through another function or from outside of the first function?
Updating a value in a function through another function or from outside of the first function?

Time:03-03

I have written a very simple code to have a scatter plot. I wondered to know how I can replace the figure by introducing a new y-axis through a second function, and updating the figure. in this example, I can plot based on the values for x, y1. I want to know if I got new values such as y2 through another function, how to update the figure?

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

CodePudding user response:

Make the Y values a global variable. You can also make x automatically adapt to the length of this, instead of hard-coding 9 elements.

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

CodePudding user response:

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)

If you want to have a different title or save to a different .png, change the function 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)

I hope this helps.

  • Related