Home > Software engineering >  Fix color for multiline updating plot matplotlib
Fix color for multiline updating plot matplotlib

Time:06-18

I have a numpy array with:

  • col[0]=time=xaxis_data
  • col[1:32]= lines for y axis.

Every second a new row of data is added to the array.

I am plotting the data and updating the plots, however I cannot get the colors of each line to stay fixed.

import numpy as np
import time
import matplotlib.pyplot as plt

 #add time column
start_measurment = time.time()
 #storing the updated data 
to_plot = np.zeros((1, 33)) 

#maybe using this? my_colors = plt.rcParams['axes.prop_cycle'][:32]()

fig,ax = plt.subplots(1,1)
ax.set_xlabel('time(s)')
ax.set_ylabel('sim. Data')
for i in range (20): #updating plot 20 times
     #simulate the data for Stack example     
    Simulated_data = (np.arange(32)*i).reshape((1, 32))
     #insert the time as col[0]
    Simulated_data = np.insert(Simulated_data, 0, [time.time()-start_measurment], axis=1) #insert time 
     #append new data to a numpy array 
    to_plot = np.append(to_plot,Simulated_data , axis=0)
     #Plot Data
    ax.plot(to_plot[:,0], to_plot[:,1:]) #Add here how to fix colours
    fig.canvas.draw()  
    time.sleep(1) 

CodePudding user response:

I don't think you can plot different colours in a single line plot statement but if you put in a nested for loop it is then possible:

import numpy as np
import time
import matplotlib.pyplot as plt

 #add time column
start_measurment = time.time()
 #storing the updated data 
to_plot = np.zeros((1, 33)) 

#maybe using this? my_colors = plt.rcParams['axes.prop_cycle'][:32]()

fig,ax = plt.subplots(1,1)
ax.set_xlabel('time(s)')
ax.set_ylabel('sim. Data')
for i in range (100): #updating plot 20 times
     #simulate the data for Stack example     
    Simulated_data = (np.arange(32)*i).reshape((1, 32))
     #insert the time as col[0]
    Simulated_data = np.insert(Simulated_data, 0, [time.time()-start_measurment], axis=1) #insert time 
     #append new data to a numpy array 
    to_plot = np.append(to_plot,Simulated_data , axis=0)
    #Plot Data
    for j in range(1,len(to_plot[0])-1):
        
        ax.plot(to_plot[:,0], to_plot[:,j:j 1],c = f"C{j}") #Add here how to fix colours
    fig.canvas.draw()  
    time.sleep(1) 
  • Related