Home > Blockchain >  Fading animated scatterplot with multiple colours
Fading animated scatterplot with multiple colours

Time:07-27

I have 3 columns of data representing 3 pixels (x1, x2, x3), that update live.

I want to:

  • animate a scatter with x1 at x=1, x2 at x=2, x3 at x=3
  • have a distinct colour for each of the pixels (x1=red, x2=blue, x3=green)
  • when updating the figure with new data, have previous scatter data fade.

I am trying to modify from: Example work so far

CodePudding user response:

It looks like you took the right approach, the only change I would suggest is creating 3 different scatter plots (one for each x values) instead of one.

See code below:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.animation import PillowWriter
import matplotlib.cm as cm

fig, ax = plt.subplots()
ax.set_xlabel('X Axis', size = 12)
ax.set_ylabel('Y Axis', size = 12)
ax.axis([0,4,0,1])
x_vals = []
y_vals = []

iterations = 100

t_vals = np.linspace(0,1, iterations)

cmaps=[cm.get_cmap('Reds'),cm.get_cmap('Blues'),cm.get_cmap('Greens')] #declaring colormaps
scatters=[ax.scatter(x_vals,y_vals,c=[],cmap=cmaps[i],vmin=0,vmax=1) for i in range(len(cmaps))] #initializing the 3 scatter plots
intensities=[[] for i in range(len(cmaps))]  #initializing intensities array

def get_new_vals():
    x = np.arange(1,4) 
    y = np.random.rand(3)
    return x,y

def update(t):
    global x_vals, y_vals, intensities
    # Get intermediate points
    new_xvals, new_yvals = get_new_vals()
    x_vals=np.hstack((x_vals,new_xvals))
    y_vals=np.hstack((y_vals,new_yvals))
   
    # Put new values in your plot
    for i in range(3):
        scatters[i].set_offsets(np.c_[x_vals[x_vals==i 1],y_vals[x_vals==i 1]])
        intensities[i]=np.concatenate((np.array(intensities[i])*0.96, np.ones(len(new_xvals[new_xvals==i 1]))))
        scatters[i].set_array(intensities[i])
        
    ax.set_title('Different colours for each x value')

ani = matplotlib.animation.FuncAnimation(fig, update, frames=t_vals,interval=50)
plt.show()

enter image description here

  • Related