2

I am working on a code to plot a heat map using matplotlib library,the problem I am facing is , instead of my (same) plot being updated for every new set of data in the loop I am getting new window of plot for each data set. I referred this good post about it but it didn't help me, may be because of limited knowledge of drawing graphs in python.Any help and suggestions in this regard will be really helpful!

Please find my code below (displaying multiple plot window) below:

import numpy as np
import scipy.io.wavfile
import wave
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = 5,2

rate, data = scipy.io.wavfile.read('test1.wav')
chunk = np.array_split(data, 682)
l = len(chunk)
count= 0
while(count<l):
    x = np.linspace(1,len(chunk[count]),num =len(chunk[count]) )
    y= np.array(chunk[count])

    fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True)
    extent = [x[0] - (x[1] - x[0]) / 2., x[-1] + (x[1] - x[0]) / 2., 0, 1]
    ax.imshow(y[np.newaxis, :], cmap="plasma", aspect="auto", extent=extent)
    ax.set_yticks([])
    ax.set_xlim(extent[0], extent[1])
    ax2.plot(x,y)
    plt.tight_layout()
    plt.draw()
    plt.pause(0.1)
    count = count +1
Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63
Laveena
  • 453
  • 1
  • 7
  • 24
  • Looks like you need to create the data structure while you are looping. Once the loop is complete then call the graph generation method. Don't call the graph function in the while loop. – Nicholas Porter Jan 30 '18 at 22:58
  • @Nicholas.. This offline version of my code has to be made online for reading real time data from audio port and plotting it simultaneously , I second on your suggestion but it wont help me in long run.. But thank you very much for your suggestion! – Laveena Jan 30 '18 at 23:02

1 Answers1

1

Well, It will be my 2nd answer to my own question :P I figured it out!

Just move this line: fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True)above while loop,so that you initialize one figure and ask this figure to be constant while the values in the plot keeps on changing.

Do addplt.cla() in the end , within the while loop so you clear up the plot from the old data else the new plot will be overwritten/plotted over old one's.

Laveena
  • 453
  • 1
  • 7
  • 24