Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: How to plot rectangle with gradient color in Plotly?

Can a shape such as a rectangle have a smooth color gradient in Plotly?

I define the shape with a solid fill color as:

shapes=[dict(
    type='rect',
    xref='x',
    yref='paper',
    x0=box_from, x1=box_to,
    y0=0, y1=1,
    fillcolor='Green',
    opacity=0.07,
    layer='below',
    line=dict(width=0),
)]

But I'd like the box not to have a solid color fill, but to have a smooth color gradient.

  • This is the example in the documentation I'm following:
    https://plotly.com/python/shapes/#highlighting-time-series-regions-with-rectangle-shapes
  • The docs on fillcolor aren't very extensive:
    https://plotly.com/python/reference/#layout-shapes-items-shape-fillcolor
  • I guess colorscales don't apply to shapes:
    https://plotly.com/python/builtin-colorscales/

My guess is the answer is a simple "not supported", but perhaps someone else knows better.

like image 426
David Parks Avatar asked Apr 01 '20 01:04

David Parks


Video Answer


1 Answers

Someone will correct me if I'm wrong but I think that no, there is no straight implementation to fill with a gradient a shape. But to achieve a similar results you could plot several lines inside the rectangle specifying decreasing rgb values.

For example I added this for loop after the first rectangle definition in the documentation code (changing also the rectangle fillcolor to white).

for i in range(100):
    fig.add_shape(type='line',
    xref="x",
    yref="y",
    x0=2.5,
    x1=3.5,
    y0=i*(2/100),
    y1=i*(2/100),
    line=dict(
                color='rgb({}, {}, {})'.format((i/100*255),(i/100*255),(i/100*255)),
                width=3,
            ))

And the result is:

enter image description here

I know it's impractical and that it can increase a bit the running time but if you care only about the aesthetic it does the job.

like image 50
Edoardo Guerriero Avatar answered Sep 27 '22 19:09

Edoardo Guerriero