我希望根据相应布尔数组的值(在本例中为annotation
)显示不同颜色的折线图部分。到目前为止,我已经尝试过这个:
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值。
如何在某些地区以不同方式为线条着色?
答案 0 :(得分:2)
以下是您的问题的有效解决方案:
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()
顺便说一下,
行walkIndex = annotation == True
至少不是必需的,因为如果将布尔数组与True
进行比较,结果将是相同的。因此,您只需写下:
positive[annotation]
答案 1 :(得分: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?