2016-06-13 73 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() 

但是,這一個加入兩種顏色,背景顏色也是可見的。

我碰到了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.ma.masked'而不是'np.nan',然後'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

順便說一下,行

walkIndex = annotation == True 

至少是沒有必要的,因爲如果你比較一個布爾數組True結果將是相同的。因此,你只需要寫:

positive[annotation]