Create dynamic updated graph with Python

2024/11/15 1:04:09

I need to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen.

I know how to use matplotlib, but the problem with matplotlib is that I can display graph only once, at the end of the script. I need to be able not only to display graph one time, but also update it on the fly, each time when data changes.

I found that it is possible to use wxPython with matplotlib to do this, but it is little bit complicate to do this for me, because I am not familiar with wxPython at all.

So I will be very happy if someone will show me simple example how to use wxPython with matplotlib to show and update simple graph. Or, if it is some other way to do this, it will be good to me too.

Update

PS: since no one answered and looked at matplotlib help noticed by @janislaw and wrote some code. This is some dummy example:


import time
import matplotlib.pyplot as pltdef data_gen():a=data_gen.aif a>10:data_gen.a=1data_gen.a=data_gen.a+1return range (a,a+10)def run(*args):background = fig.canvas.copy_from_bbox(ax.bbox)while 1:time.sleep(0.1)# restore the clean slate backgroundfig.canvas.restore_region(background)# update the dataydata = data_gen()xdata=range(len(ydata))line.set_data(xdata, ydata)# just draw the animated artistax.draw_artist(line)# just redraw the axes rectanglefig.canvas.blit(ax.bbox)data_gen.a=1
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], animated=True)
ax.set_ylim(0, 20)
ax.set_xlim(0, 10)
ax.grid()manager = plt.get_current_fig_manager()
manager.window.after(100, run)plt.show()

This implementation have problems, like script stops if you trying to move the window. But basically it can be used.

Answer

Here is a class I wrote that handles this issue. It takes a matplotlib figure that you pass to it and places it in a GUI window. Its in its own thread so that it stays responsive even when your program is busy.

import Tkinter
import threading
import matplotlib
import matplotlib.backends.backend_tkaggclass Plotter():def __init__(self,fig):self.root = Tkinter.Tk()self.root.state("zoomed")self.fig = figt = threading.Thread(target=self.PlottingThread,args=(fig,))t.start()def PlottingThread(self,fig):     canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=self.root)canvas.show()canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)toolbar = matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg(canvas, self.root)toolbar.update()canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)self.root.mainloop()

In your code, you need to initialize the plotter like this:

import pylab
fig = matplotlib.pyplot.figure()
Plotter(fig)

Then you can plot to it like this:

fig.gca().clear()
fig.gca().plot([1,2,3],[4,5,6])
fig.canvas.draw()
https://en.xdnf.cn/q/72283.html

Related Q&A

Converting a nested dictionary to a list

I know there are many dict to list questions on here but I cant quite find the information I need for my situation so Im asking a new quetion.Some background: Im using a hierarchical package for my mod…

Pandas dataframe : Operation per batch of rows

I have a pandas DataFrame df for which I want to compute some statistics per batch of rows. For example, lets say that I have a batch_size = 200000. For each batch of batch_size rows I would like to ha…

Combining grid/pack Tkinter

I know there have been many questions on grid and pack in the past but I just dont understand how to combine the two as Im having difficulties expanding my table in both directions (row/column).Buttons…

Mocking assert_called_with in Python

Im having some trouble understanding why the following code does not pass:test.pyimport mock import unittestfrom foo import Fooclass TestFoo(unittest.TestCase):@mock.patch(foo.Bar)def test_foo_add(self…

Python select() behavior is strange

Im having some trouble understanding the behavior of select.select. Please consider the following Python program:def str_to_hex(s):def dig(n):if n > 9:return chr(65-10+n)else:return chr(48+n)r = wh…

Moving items up and down in a QListWidget?

In a QListWidget I have a set of entries. Now I want to allow the user to sort (reorder) these entries through two buttons (Up/Down).Heres part of my code:def __init__(self):QtGui.QMainWindow.__init__(…

How to resize a tiff image with multiple channels?

I have a tiff image of size 21 X 513 X 513 where (513, 513) is the height and width of the image containing 21 channels. How can I resize this image to 21 X 500 X 375?I am trying to use PILLOW to do …

Losing elements in python code while creating a dictionary from a list?

I have some headache with this python code.print "length:", len(pub) # length: 420pub_dict = dict((p.key, p) for p in pub)print "dict:", len(pub_dict) # length: 163If I understand t…

How to set Font size or Label size to fit all device

How to set kivy font size or label size so that it will fit all phone-device screen? (fit by means does not overlap with the boundary, rectangle, or even the screen)I know the Buttons and some other W…

Using tweepy to access Twitters Streaming API

Im currently having trouble getting example code for using tweepy to access Twitters Streaming API to run correctly (err...or at least how I expect it to run). Im using a recent clone of tweepy from Gi…