我想根据相应布尔数组的值(在本例中)以不同颜色显示折线图的各个部分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()
Run Code Online (Sandbox Code Playgroud)
但这一个将两种颜色结合在一起,并且背景颜色也是可见的。
我遇到了BoundaryNorm
但我认为它需要 y 值。
有什么想法如何在某些地区以不同的方式为线条着色吗?
以下是针对您的问题的有效解决方案:
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()
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这条线
walkIndex = annotation == True
Run Code Online (Sandbox Code Playgroud)
至少没有必要,因为如果将布尔数组与True
结果进行比较,结果将是相同的。因此,你只需写:
positive[annotation]
Run Code Online (Sandbox Code Playgroud)
我使用以下代码解决了它,但我认为这是一个相当“粗糙”的解决方案
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')
Run Code Online (Sandbox Code Playgroud)
类似于这篇文章中的解决方案: Pyplot - Change color of line if data is less than zero?
归档时间: |
|
查看次数: |
9820 次 |
最近记录: |