2017-03-27 95 views
1

我試圖在此動畫中爲每個點獲取不同的顏色。我想傳遞數組c_state作爲每個點的hsv元組的hue值。到目前爲止,我嘗試過的一切都失敗我在animate函數嘗試使用這樣的:matplotlib動畫中的數組的不同顏色點

particles.set_color(pbox.color[:,0],1.0,1.0) 

但我得到警告說,只有長度爲1的陣列可以轉換爲標量。 我也嘗試使用np.random製作長度爲3的數組,並試圖將它們轉換爲rgb-tuples,但那也不起作用。我很難找到正確的數據結構傳遞給ax.plot的顏色變量。 顏色只需設置一次,在動畫過程中不需要更改。

import matplotlib.pyplot as plt 
import matplotlib.animation as anim 
import numpy as np 
import colorsys 
from random import random 

n = 250 

class ParticleBox: 

    def __init__(self,i_state,c_state): 
     self.i_state = np.asarray(i_state, dtype=float) 
     self.c_state = np.asarray(c_state, dtype=float) 

     self.state = self.i_state.copy() 
     self.color = self.c_state.copy() 

i_state = -5 + 10 * np.random.random((n, 2)) 
c_state = np.random.random((n, 1)) 

pbox = ParticleBox(i_state, c_state) 

fig = plt.figure() 
ax = fig.add_subplot(111, xlim=(-10,10), ylim=(-10,10)) 

particles, = ax.plot([], [], 'o', ms=5) 

def init(): 
    global pbox 
    particles.set_data([],[]) 

    return particles, 

def animate(i): 
    global pbox, ax, fig 
    particles.set_data(pbox.state[:,0],pbox.state[:,1]) 

    return particles, 

ani = anim.FuncAnimation(fig, animate, frames = 500, 
         interval = 10, blit=True, 
         init_func=init) 
plt.show() 
+1

*如何*已經失敗了,那麼遠? – SiHa

+0

我編輯了這個問題。 – Ebo

回答

1

線圖plt.plot()在matplotlib有且只有一種顏色。您無法爲其細分設置不同的顏色。你需要的是散點圖plt.scatter。可以更新在這種情況下使用

sc = plt.scatter(x,y, c=.., s =.., cmap="hsv") 
sc.set_offsets(np.c_[x,y]) # set positions 
sc.set_array(color) # set color 

color將值0和1的那些值之間的一維數組的散點圖將被映射到使用hsv顏色表,這是在cmap參數指定HSV顏色分散。

enter image description here

完整代碼將如下所示:

import matplotlib.pyplot as plt 
import matplotlib.animation as anim 
import numpy as np 

n = 140 

class ParticleBox: 
    def __init__(self,i_state,c_state): 
     self.i_state = np.asarray(i_state, dtype=float) 
     self.c_state = np.asarray(c_state, dtype=float) 
     self.state = self.i_state.copy() 
     self.color = self.c_state.copy() 
    def iterate(self): 
     self.state += (np.random.random((n, 2))-0.5)/3. 
     self.state[self.state > 10.] = 10 
     self.state[self.state < -10] = -10 
     self.color += (np.random.random(n)-0.5)/89. 
     self.color[self.color>1.] = 1. 
     self.color[self.color<0] = 0. 


i_state = -5 + 10 * np.random.random((n, 2)) 
c_state = np.random.random(n) 

pbox = ParticleBox(i_state, c_state) 

fig = plt.figure() 
ax = fig.add_subplot(111, xlim=(-10,10), ylim=(-10,10)) 

particles = ax.scatter([], [], c=[],s=25, cmap="hsv", vmin=0, vmax=1) 

def animate(i): 
    pbox.iterate() 
    particles.set_offsets(pbox.state) 
    particles.set_array(pbox.color) 
    return particles, 

ani = anim.FuncAnimation(fig, animate, frames = 140, 
         interval = 10, blit=True) 

plt.show() 
+0

非常好,這正是我一直在尋找的!謝謝! – Ebo

+0

我如何去做粒子大小的動態呢?我試過傳遞另一個'set_array()',但是這使得所有的粒子真的很小。 – Ebo

+0

'.set_array()'確定顏色。大小使用'.set_sizes()'。 – ImportanceOfBeingErnest

相關問題