Change color of lineplot mid-line segment

Viewed 350

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:

Picture of what I get. Only line segments that are completely below zero are blue

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

Picture of what I want. All lines below zero are blue

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

1 Answers

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.

enter image description here

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