2017-02-28 329 views
1

我是matplotlib动画的新手,我正在试图为散点图创建动画,点向右移动时会逐渐变红,而向左移动的点会逐渐变为蓝色。代码不能完美工作,因为它不会逐渐改变点的颜色。当我暂停动画并使其最大化时,颜色的逐渐变化突然出现,当我播放它时,它也是一样的。 Here是动画链接。最终的图像应该是这样的: Final static image after animation 但是,动画并未显示颜色逐渐变化,因为您可以在视频中看到。Matplotlib动画散点图python。逐渐改变点的颜色

这是代码,我非常感谢你的帮助。由于

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import numpy as np 
import pandas as pd 
class AnimatedScatter(object): 
    """An animated scatter plot using matplotlib.animations.FuncAnimation.""" 
    def __init__(self, numpoints=5): 
     self.numpoints = numpoints 
     self.stream = self.data_stream() 

     # Setup the figure and axes... 
     self.fig, self.ax = plt.subplots() 
     # Then setup FuncAnimation. 

     self.ani = animation.FuncAnimation(self.fig, self.update, interval=500, 
              init_func=self.setup_plot, blit=True,repeat=False) 

     self.fig.canvas.mpl_connect('button_press_event',self.onClick) 
     #self.ani.save("animation.mp4") 
    def setup_plot(self): 
     """Initial drawing of the scatter plot.""" 
     t=next(self.stream) 
     x, y, c = t[:,0],t[:,1],t[:,2] 
     self.scat = self.ax.scatter(x, y, c=c, s=50, animated=True) 
     self.ax.axis([-15, 15, -10, 10]) 

     # For FuncAnimation's sake, we need to return the artist we'll be using 
     # Note that it expects a sequence of artists, thus the trailing comma. 
     return self.scat, 

    def data_stream(self): 
     #f=pd.read_csv("crc_viz.csv") 
     columns = ['TbyN','CbyS'] 
     #f=f[['TbyN','CbyS']] 
     index=range(1,self.numpoints+1) 
     x=10*(np.ones((self.numpoints,1))-2*np.random.random((self.numpoints,1))) 
     y = 5*(np.ones((self.numpoints,1))-2*np.random.random((self.numpoints,1))) 
     f=np.column_stack((x,y)) 
     f=pd.DataFrame(f,columns=columns) 
     print f 
     f['new_cbys'] = f['CbyS'] 
     f['new_cbys'][f['new_cbys']<0] = -1 
     f['new_cbys'][f['new_cbys']>0] = 1 
     f=f[:self.numpoints] 
     cbys=np.array(list(f['CbyS'])) 
     sign = np.array(list(f['new_cbys'])) 
     x = np.array([0]*self.numpoints) 
     y = np.array(f['TbyN']) 
     c = np.array([0.5]*self.numpoints) 
     t = [(255,0,0) for i in range(self.numpoints)] 
     data=np.column_stack((x,y,c)) 

     x = data[:, 0] 
     c = data[:,2] 
     while True: 
      #print xy 
      #print cbys 
      if not pause: 

       for i in range(len(x)): 
        if sign[i]==1: 
         if x[i]<cbys[i]-0.1: 
          x[i]+=0.1 

          c[i]+=0.05 
         else: 
          x[i]=cbys[i] 
        elif sign[i]==-1: 
         if x[i]>cbys[i]+0.1: 
          x[i]-=0.1 
          c[i]-=0.05 
         else: 
          x[i]=cbys[i] 
       print c 

       #print data 
       #print c 
      yield data 
    def onClick(self,event): 
     global pause 
     pause ^=True 
    def update(self, i): 
     """Update the scatter plot.""" 
     data = next(self.stream) 
     print data[:,2] 
     # Set x and y data... 
     self.scat.set_offsets(data[:, :2]) 
     # Set colors.. 
     self.scat.set_array(data[:,2]) 


     return self.scat, 
    def save(self): 
     plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe' 
     self.mywriter = animation.FFMpegWriter() 
     self.ani.save("myMovie.mp4",writer=self.mywriter) 
     self.show() 
    def show(self): 
     #mng = plt.get_current_fig_manager() 
     #mng.window.state('zoomed') 
     plt.show() 


pause = False 
if __name__ == '__main__': 
    a = AnimatedScatter(10) 
    a.show() 
    #a.save() 

回答

0

你的问题是,散点图在每次迭代重新绘制,重整化的色彩来的c最小和最大的价值。因此,即使在开始时,色彩映射中的最小和最大颜色也会出现点对应。

解决方案将使用从一开始就是绝对的颜色标准化。最简单的方法是使用vminvmax关键字参数。

ax.scatter(x, y, c=c, vmin=-1.5, vmax=2) 

(这意味着c=-1.5值在颜色表最低的颜色和c=2对应于最高。)

现在它可能有点难以找到适当的值,作为值在一个无限循环中不断变化,所以你需要根据用例自己找出合适的值。