如何让遮罩数组为pyplot中的整个段着色?

2024-10-01 07:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直希望在y值超过阈值(在本例中为30)时将时间序列涂成红色

我仔细阅读并找到了this article,它给出了两个主要建议:要么使用遮罩数组,要么按段构建颜色贴图。当我尝试重新处理颜色贴图解决方案时,返回一个关键错误[0],但当我尝试使用遮罩数组时,我得到以下结果:

enter image description here

这是非常接近我需要的,但我似乎找不到一种方法,使整条线的颜色高于阈值,只有部分。如何使整条线在阈值线上方显示为红色

这是我用来生成绘图的代码:

#Note: This isn't my source data, but will show the same effect
ut9_ffwi = [2, 15, 14, 28, 40, 49, 27, 36, 24, 12]
ut9_time = range(0, 10, 1)

threshold = 30
ut9_ffwi = np.ma.array(ut9_ffwi)
ut201_ffwi = np.ma.array(ut201_ffwi)
mask = ma.masked_where(ut9_ffwi <= threshold, ut9_ffwi)

# Plot
plt.plot(ut9_time, ut9_ffwi)
# Highlight values above 30
plt.plot(ut9_time, mask, 'r', linewidth=3.2)
# Plot a horizontal line for threshold
plt.axhline(y = threshold, color='r', linestyle='-')
plt.xticks(rotation = 90)
plt.legend(['FFWI Data', 'Threshold'])

Tags: thresholdtimeplot颜色nppltmask阈值
1条回答
网友
1楼 · 发布于 2024-10-01 07:29:57

您可以按照Multicolored Line的指南进行操作。注释中指出的技巧是使用非常精细的网格进行插值,这样可以使线段相对靠近截止点。这里的示例使用了您的变量,但为了真正说明这一点,它有点嘈杂

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

np.random.seed(410112)
ut9_ffwi = np.random.randint(0, 50, 100)
ut9_time = range(len(ut9_ffwi))

# Interpolate using a very fine grid
Nfine = 500
x = np.linspace(ut9_time[0], ut9_time[-1], len(ut9_time)*Nfine)
y = np.interp(x, ut9_time, ut9_ffwi)

# Now to color the segments
cmap = ListedColormap(['b', 'r'])
norm = BoundaryNorm([0, 30, np.inf], cmap.N)

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(y)
lc.set_linewidth(3)
plt.gca().add_collection(lc)

plt.xlim(x.min(), x.max())
plt.ylim(y.min(), y.max())

plt.show()

enter image description here


如果设置Nfine=1,它将进行打印,就像没有插值到更精细的栅格一样,并且您将看到线段穿过边界出血。越大的Nfine是噪声数据的边界越清晰,尽管这是以绘制很多点为代价的

enter image description here

相关问题 更多 >