Matplotlib中一个图表中有多种颜色

3
有没有一种方法可以在Python Matplotlib中针对某个阈值改变图表的颜色?
plt.plot(temp)
plt.plot((0, len(temp)), (100, 100), 'b-')
plt.ylabel('Some data')
plt.show()

其中temp包含一些数据 最终的图像看起来像这样: enter image description here

现在是否有可能显示此行上方的数据(在此示例中为100)以其他颜色?


1
数据以连续图形的形式呈现很重要吗?为什么不只将数据绘制成点呢? - Zachi Shtain
1个回答

4
你可以使用掩码数组来绘制多条线。这是一个示例:
找到曲线和阈值线之间的交点,并将这些点插入原始数据中。然后,您可以使用掩码数组两次调用plot()
import numpy as np
import pylab as pl

def threshold_plot(x, y, th, fmt_lo, fmt_hi):
    idx = np.where(np.diff(y > th))[0]
    x_insert = x[idx] + (th - y[idx]) / (y[idx+1] - y[idx]) * (x[idx+1] - x[idx])
    y_insert = np.full_like(x_insert, th)

    xn, yn = np.insert(x, idx+1, x_insert), np.insert(y, idx+1, y_insert)

    mask = yn < th
    pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_hi, lw=2)

    mask = yn > th
    pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_lo)
    pl.axhline(th, color="black", linestyle="--")

x = np.linspace(0, 3 * np.pi, 50)
y = np.random.rand(len(x))
threshold_plot(x, y, 0.7, "b", "r")

结果:

在此输入图片描述


(注:该内容为HTML标签,已翻译为中文)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接