简体   繁体   中英

Change color of lineplot mid-line segment

I need to plot a line plot. I want to plot all parts of the lineplot that are below zero blue, and all parts above red.

Here's what I managed so far:

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()

Here's what I get with this script:

我得到的图片。只有完全低于零的线段是蓝色的

But what I want is for the color to change at the threshold of 0, like this example (that I've modified to show what I want):

我想要的图片。零以下的所有线都是蓝色的

I've looked at some suggestions here, for example this here: Plot: color all larger than different color

But I get the same figure with that solution. It seems that the solution lies in the fact that all their line segments are incredibly short, so you don't notice that a segment that passes the threshold doesn't change color at the threshold, and only the next segment is drawn in a different color.

Is there a straightforward way to do this? Or do I have to separate the line segments that cross the threshold manually?

Thank you

It seems that the solution lies in the fact that all their line segments are incredibly short, so you don't notice that a segment that passes the threshold doesn't change color at the threshold, and only the next segment is drawn in a different color.

You could just interpolate your data such that this holds true for your data as well.

在此处输入图像描述

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM