Matplotlib绘制随着时间推移旧点逐渐消失的点

San*_*wal 1 python matplotlib python-3.x

我想通过matplotlib实现两个目标:

  • 动态更新散点图
  • 慢慢使在先前迭代中绘制的点更加透明。

目前,我可以使用色图实现相反的目标。也就是说,我可以随时间绘制点,但是最近的点看起来更加透明。

使用cmap或其他工具能否在matplotlib上获得“褪色”效果?谢谢!我的代码如下:

def plotter_fader(iterations = 100, stay_open = True):
# Set up plot
fig, ax = plt.subplots()
x_data = []
y_data = []
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
t_vals = np.linspace(0,1, iterations)
cmap = (0.09803921568627451, 0.09803921568627451, 0.09803921568627451, .05)
for t in t_vals:
    # Get intermediate points
    intermediate = (1-t)*A + t*B
    new_xvals, new_yvals = ... #Get these through some process
    x_vals.extend(new_xvals)
    y_vals.extend(new_yvals)

    # Put new values in your plot
    plt.plot(x_vals, y_vals, '.', color = cmap)

    # Recompute plot limits
    ax.relim()

    # Set title and wait a little bit for 'smoothness'
    ax.set_xlabel('X Axis', size = 12)
    ax.set_ylabel('Y Axis', size = 12)
    ax.set_title('Time: %0.3f' %t)
    ax.autoscale_view()
    fig.canvas.draw()
    time.sleep(0.005)

# Stay open after plotting ends
while stay_open:
    pass
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 5

与散点图一样,您可以定义一个值数组和一个将这些值映射到颜色的色图。您可以在每次迭代中更改此数组,以使较旧的点具有不同的值。

在下面的代码中,我们将0值设为透明,将1值设为深蓝色,然后使用这些颜色创建一个颜色图。
在每次迭代中,将旧值乘以小于1的数字,将新值设置为1。

因此,运行动画将产生渐变点。

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

fig, ax = plt.subplots()
ax.set_xlabel('X Axis', size = 12)
ax.set_ylabel('Y Axis', size = 12)
ax.axis([0,1,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]]
cmap = LinearSegmentedColormap.from_list("", colors)
scatter = ax.scatter(x_vals,y_vals, c=[], cmap=cmap, vmin=0,vmax=1)

def get_new_vals():
    n = np.random.randint(1,5)
    x = np.random.rand(n)
    y = np.random.rand(n)
    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('Time: %0.3f' %t)

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

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明