I have a piece of code that takes real time audio signal from audio jack of my laptop and plots its graph after some basic filtering. The problem I am facing is that the rea
This is a little long for a comment, and since you're asking for suggestions I think it's a semi-complete answer. There's more info and examples online about getting realtime plotting with matplotlib, if you need ideas beyond what's here. The library wasn't designed for this, but it's possible.
First step, profile the code. You can do this with
import cProfile
cProfile.run('soundplot(stream)')
That will show where most of the time is being spent. Without doing that, I'll give a few tips, but be aware that profiling may show other causes.
First, you want to eliminate redundant function calls in the function soundplot
. Both of the following are unnecessary:
plt.xlim(extent[0], extent[1])
plt.ylim(-50000000, 50000000)
They can be called once in initialization code. imshow
updates these automatically, but for speed you shouldn't call that every time. Instead, in some initialization code outside the function use im=imshow(data, ...)
, where data is the same size as what you'll be plotting (although it may not need to be). Then, in soundplot
use im.set_data(y1[np.newaxis, :])
. Not having to recreate the image object each iteration will speed things up immensely.
Since the image object remains through each iteration, you'll also need to remove the call to cla()
, and replace it with either show()
or draw()
to have the figure draw the updated image. You can do the same with the line on the second axis, using line.set_ydata(y)
.
Please post the before and after rate it runs at, and let me know if that helps.
Edit: some quick profiling of similar code suggests a 100-500x speedup, mostly from removing cla()
.
Also looking at your code, the reason for it slowing down is that cla
isn't ever called on the first axis. Eventually there will be hundreds of images drawn on that axis, slowing matplotlib to a crawl.