How to make dynamic graphics in Python 3?

Asked

Viewed 1,160 times

2

I’m doing a program for Raspberry Pi that scans temperature sensors and stores these readings in a buffer. I need to make a dynamic graph that shows the relationship between temperature and current time. I tried using the matplotlib library, but I can’t update this graph.

In the code below, when I use the append method I add the values obtained in the temperature reading.

import matplotlib.pyplot as plt

temperatura = [10, 20, 30 ,40 , 50 ,60 , 70, 80]

tempo = [1, 2, 3, 4, 5, 6, 7, 8]

plt.plot(tempo, temperatura )

plt.ylabel('Temperatura (C°)')

plt.xlabel('Tempo (S)')

plt.show()

temperatura.append(90)

tempo.append(9)

plt.plot(tempo, temperatura )

plt.show()

When running the program the graph with the initial values is shown, but only when closing the graph does it open the other graph with the updated values!

  • You have two plt.show() in your code.

  • Yes, to try to update the chart!

  • According to the documentation it is possible to use plt.show(block=False) so that he does not wait for the drawing to be closed.

  • Said "according to the documentation" because it says it is an experimental implementation :-)

  • This link has what you are looking for https://pythonprogramming.net/python-matplotlib-live-updating-graphs/

1 answer

1


Using the function animation of matplotlib it is possible to do it in a simple way, using your code I created an example, I’m taking the temperature randomly, random values between 0 and 100 to demonstrate, the time in this case is being increased by +1, follows a small gif of code running:

inserir a descrição da imagem aqui

Follows the code:

from random import randint
import matplotlib.pyplot as plt
import matplotlib.animation as animation



fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

xs = [1, 2, 3, 4, 5, 6, 7, 8]
ys = [10, 20, 30 ,40 , 50 ,60 , 70, 80]


#incremento partindo dos últimos valores de cada lista
temperatura=80
tempo=8;

#função para animar
def animate(i, xs, ys):
    global temperatura
    global tempo

    #incremento
    #temperatura= temperatura+10
    temperatura= randint(0, 100)
    tempo = tempo + 1

    #append índice do tempo e temperatura
    xs.append(tempo)
    ys.append(temperatura)


    # desenhar x e y
    ax.clear()
    ax.plot(xs, ys)


    plt.title('Temperatura Atual e Tempo')
    plt.ylabel('Temperatura')

# altere o valor do interval para que que o frame seja atualizado de maneira mais rápida ou não
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)
plt.show()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.