【问题标题】:Multiple colors in the one graph in MatplotlibMatplotlib 中一张图中的多种颜色
【发布时间】:2015-11-04 20:29:46
【问题描述】:

有没有办法在 python Matplotlib 中将图形的颜色更改为某个阈值?

plt.plot(temp)
plt.plot((0, len(temp)), (100, 100), 'b-')
plt.ylabel('Some data')
plt.show()

其中 temp 包含一些数据 最终图像看起来像这样:

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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您可以使用掩码数组绘制多条线。这是一个例子:

找到曲线和阈值线的交点,并将这些点插入到原始数据中。然后你可以用掩码数组调用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")

结果:

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多