2016-06-13 6 views
1

対応するブール値配列(この場合はannotation)の値に応じて、線グラフの各部分を異なる色で表示したいとします。これまで私はこれを試した:Pyplotの対応する値に応じて線の色が異なります

plt.figure(4) 
plt.title("Signal with annotated data") 
plt.plot(resampledTime, modulusOfZeroNormalized, 'r-',) 
walkIndex = annotation == True 
plt.plot(resampledTime[~walkIndex], modulusOfZeroNormalized[~walkIndex], label='none', c='b') 
plt.plot(resampledTime[walkIndex], modulusOfZeroNormalized[walkIndex], label='some', c='g') 
plt.show() 

しかし、これは2つの色を結合し、背景色も表示されます。

私はBoundaryNormに出くわしましたが、y値が必要だと思います。

いくつかの地域で線を色分けする方法はありますか?

The image with different colors

答えて

1

私は、次のコードを使用して、それを解決し、私はそれが非常に「ラフ」ソリューションこの記事内の溶液と同様に

plt.figure(4) 
plt.title("Signal with annotated data") 

walkIndex = annotation == True 
positive = modulusOfZeroNormalized.copy() 
negative = modulusOfZeroNormalized.copy() 

positive[walkIndex] = np.nan 
negative[~walkIndex] = np.nan 
plt.plot(resampledTime, positive, label='signal', c='r') 
plt.plot(resampledTime, negative, label='signal', c='g') 

思う: Pyplot - change color of line if data is less than zero?

+0

'np.nan'の代わりに' np.ma.masked'を使うと、 'matplotlib'はそれを除外します – Bart

1

次問題の有効な解決策です:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.collections import LineCollection 

# construct some data 
n = 30 
x = np.arange(n+1)   # resampledTime 
y = np.random.randn(n+1)  # modulusOfZeroNormalized 
annotation = [True, False] * 15 

# set up colors 
c = ['r' if a else 'g' for a in annotation] 

# convert time series to line segments 
lines = [((x0,y0), (x1,y1)) for x0, y0, x1, y1 in zip(x[:-1], y[:-1], x[1:], y[1:])] 
colored_lines = LineCollection(lines, colors=c, linewidths=(2,)) 

# plot data 
fig, ax = plt.subplots(1) 
ax.add_collection(colored_lines) 
ax.autoscale_view() 
plt.show() 

Colored lines

そして、あなたはTrueにブール配列を比較した場合、結果は同じになりますので、やり方によって、ライン

walkIndex = annotation == True 

は、少なくともではない必要があります。したがって、次のように書いてください:

関連する問題