我有3列数据,代表3个像素(x1,x2,x3),实时更新。
我想:
- 设置散点动画,x=1时为x1,x=2时为x2,x=3时为x3
- 每个像素具有不同的颜色(x1=红色,x2=蓝色,x3=绿色)
- 当用新数据更新图形时,使先前的散射数据褪色。
我正在尝试修改自:Matplotlib Plot Points Over Time Where Old Points Fade
然而,我无法为x的每个值(x=1,x=2,x=3)分配不同的颜色:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.animation import PillowWriter
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 = []
intensity = []
iterations = 100
t_vals = np.linspace(0,1, iterations)
colors = [[0,0,1,0],[0,0,1,0.5],[0,0.2,0.4,1], [1,0.2,0.4,1]]
cmap = LinearSegmentedColormap.from_list("", colors)
scatter = ax.scatter(x_vals,y_vals, c=[], cmap=cmap, vmin=0,vmax=1)
def get_new_vals():
x = np.arange(1,4) # TODO: ASSOCIATE COLOUR WITH EACH X VALUE
y = np.random.rand(3)
return list(x), list(y)
def update(t):
global x_vals, y_vals, intensity
# Get intermediate points
new_xvals, new_yvals = get_new_vals()
x_vals.extend(new_xvals)
y_vals.extend(new_yvals)
# Put new values in your plot
scatter.set_offsets(np.c_[x_vals,y_vals])
#calculate new color values
intensity = np.concatenate((np.array(intensity)*0.96, np.ones(len(new_xvals))))
scatter.set_array(intensity)
# Set title
ax.set_title('Different colors for each x value')
ani = matplotlib.animation.FuncAnimation(fig, update, frames=t_vals,interval=50)
plt.show()
1条答案
按热度按时间p1tboqfb1#
看起来你采取了正确的方法,我建议的唯一变化是创建3个不同的散点图(每个
x
值一个)而不是一个。代码如下: