【问题标题】:Change color of lineplot mid-line segment更改线图中线段的颜色
【发布时间】:2020-06-17 21:14:49
【问题描述】:

我需要绘制一个线图。我想绘制低于零蓝色的线图的所有部分,以及高于红色的所有部分。

这是我到目前为止所管理的:

import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 40)
y = np.random.random(len(x))-0.5
da = xr.DataArray(y, dims=('x',), coords={'x':x})

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1, 1, 1)
da.plot(ax=ax, color='red', linewidth=3)
da.where(y<0).plot(ax=ax, color='blue', linewidth=3)
plt.show()

这是我使用此脚本得到的结果:

但我想要的是颜色在阈值 0 处发生变化,就像这个例子(我已经修改以显示我想要的):

我在这里查看了一些建议,例如这里:Plot: color all larger than different color

但我得到与该解决方案相同的数字。似乎解决方案在于它们的所有线段都非常短,因此您不会注意到通过阈值的线段不会在阈值处改变颜色,并且只有下一个线段以不同的方式绘制颜色。

有没有一种简单的方法可以做到这一点?还是我必须手动分离跨越阈值的线段?

谢谢

【问题讨论】:

    标签: python matplotlib python-xarray


    【解决方案1】:

    似乎解决方案在于它们的所有线段都非常短,因此您不会注意到通过阈值的线段不会在阈值处改变颜色,而只会绘制下一个线段用不同的颜色。

    您可以对数据进行插值,这样您的数据也同样适用。

    import numpy as np
    import xarray as xr
    import matplotlib.pyplot as plt
    
    xx = np.linspace(0, 1, 40)
    yy = np.random.random(len(xx))-0.5
    
    x = np.linspace(0, 1, 4000)
    y = np.interp(x, xx, yy) # linear piecewise interpolation
    
    da = xr.DataArray(y, dims=('x',), coords={'x':x})
    fig = plt.figure(figsize=(12,6))
    ax = fig.add_subplot(1, 1, 1)
    da.plot(ax=ax, color='red', linewidth=3)
    da.where(y<0).plot(ax=ax, color='blue', linewidth=3)
    plt.show()
    

    【讨论】:

    • 谢谢。这是一个好主意,但也有一些复杂性。当然,我的数据不是两个 numpy 数组,而是一个 xarray 数据集,所以我需要对其进行插值。另外,我的 x 轴是一个时间维度,而不仅仅是一个浮点数组。我给了你一个赞成票,但在我接受这个作为答案之前,我想看看其他人是否提出了另一种解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2019-09-03
    • 2020-08-28
    • 1970-01-01
    • 2019-12-31
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多