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


