2016-03-24 15 views
1

ランダムウォークを生成してプロットするコードがあります。しかし、私はジャンプの大きさに応じて各行の色を付ける必要があります。私はその後、私は必要な色のドットの束を得る Python:matplotlib:ジャンプのサイズでランダムウォークに線を塗る

plt.scatter(x, y, c=bigness) 

に最後から二番目の行を変更した場合、今

import matplotlib.pyplot as plt 
import numpy as np 
import random 

def randomwalk(N): 
    x, y, bigness = np.zeros((N)), np.zeros((N)), np.zeros((N)) 
    for n in range(0,N): 
     angle = random.random() * 2*np.pi 
     jump = np.random.normal(0, 50) 

     x[n] = x[n-1] + (np.cos(angle) * jump) 
     y[n] = y[n-1] + (np.sin(angle) * jump) 
     bigness[n] = abs(jump)  
    return x, y, bigness 

x, y, bigness = randomwalk(100) 

plt.plot(x, y) 
plt.show() 

、ない行は、それらに参加しない:これは私のコードです。逆に、「プロット」機能は個々の着色のためのオプションを有していない。

"plot"関数の行は必要ですが、 "scatter"関数の色付けが必要です。これはどうすればいいですか?

+1

http://matplotlib.org/examples/pylab_examples/multicolored_line.html – tom

答えて

0

ライン全体をプロットするのではなく、そのセグメントを色の濃さに基づいてプロットします。

import matplotlib.pyplot as plt 
import numpy as np 
import random 

def randomwalk(N): 
    x, y, bigness = np.zeros((N)), np.zeros((N)), np.zeros((N)) 
    for n in range(0,N): 
     angle = random.random() * 2*np.pi 
     jump = np.random.normal(0, 50) 

     x[n] = x[n-1] + (np.cos(angle) * jump) 
     y[n] = y[n-1] + (np.sin(angle) * jump) 
     bigness[n] = abs(jump)  
    return x, y, bigness 

def random_color(bigness): 
    return plt.cm.gist_ncar(bigness/100) 

x, y, bigness = randomwalk(100) 

xy = zip(x,y) 
fig, ax = plt.subplots() 
for start, stop, b in zip(xy[:-1], xy[1:], bigness): 
    x, y = zip(start, stop) 
    ax.plot(x, y, color=random_color(b)) 

plt.show() 

美しい汚い結果

enter image description here

0

は手動LineCollectionを作成し、bignessにより、各セグメントを色付けすることができます

import matplotlib as mpl 
import matplotlib.pyplot as plt 
import numpy as np 
pairs = np.array(list(zip(x, y))).reshape(-1, 1, 2) 
segments = np.concatenate((pairs[:-1], pairs[1:]), axis=1) 
lc = mpl.collections.LineCollection(segments) 
lc.set_array(bigness) 
f, ax = plt.subplots() 
ax.add_collection(lc) 
ax.autoscale_view() 
plt.show() 

デフォルト以外のカラーマップとノルムを指定するには、引数cmapnormmpl.collections.LineCollectionに渡します。

関連する問題