Black Lives Matter. Please consider donating to Black Girls Code today.

It is possible to fill area with different colors on a line plot?

Hi! i want to fill an area based on y values: red to negative, green to positives. How can i do that?

image

I don’t know how to it with one single trace, but here is a solution using numpy masks:

import plotly.graph_objects as go
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
mask = y >= 0
fig = go.Figure(go.Scatter(x=x[mask], y=np.sin(x)[mask], mode='lines',
                           fill='tozeroy', fillcolor='green'))
fig.add_trace(go.Scatter(x=x[~mask], y=y[~mask], mode='lines', fill='tozeroy', fillcolor='red'))

fig.show()

Thank you for your answer! But i want to do it with a single trace

I don’t think you can. That would be a new mode for the fill argument of Scatter traces.

Ok, thanks for your help!!!

@yuricda96 If your usecase of having only one trace is so that the legend behaves as a single trace, you can do the following:

  • Hide the legend for one of the two traces showlegend=False
  • Put both traces in the same legend group (e.g. legendgroup="my-trace")

This way you will only see one trace for the two and clicking on the legend shows/hides both traces at once.

You can also set the line color and fillcolor differently to have continuity of the line with different fill colors if necessary.

Hope this can be of help.

1 Like