lucky1928
lucky1928

Reputation: 8905

plotly express plot with filled rect in background

How to move below fill rect in background layer?

import numpy as np
import plotly.express as px

def plot(x,y):
    fig = px.scatter(
        x=x,
        y=y,
        error_y=[0] * len(y),
        error_y_minus=y
    )

    fig.add_vrect(x0=0, x1=np.pi, line_width=0, fillcolor="pink")
    tickvals = [0,np.pi/2,np.pi,np.pi*3/2,2*np.pi]
    ticktext = ["0","$\\frac{\pi}{2}$","$\pi$","$\\frac{3\pi}{4}$","$2\pi$"]
    layout = dict(
        title="demo",
        xaxis_title="X",
        yaxis_title="Y",
        title_x=0.5,   
        margin=dict(l=10,t=20,r=0,b=40),
        height=300,
        xaxis=dict(
            tickangle=0,
            tickvals = tickvals,
            ticktext=ticktext,
        ),
        yaxis=dict(
            showgrid=True,
            zeroline=False,
            showline=False,
            showticklabels=True
        )
    )

    fig.update_traces(
        marker_size=14,
    )    
    fig.update_layout(layout)
    
    fig.show()
    return

n = 20
x = np.linspace(0.0, 2*np.pi, n)
y = np.sin(x)

plot(x,y)

Current output: enter image description here

Upvotes: 0

Views: 1127

Answers (1)

Eivind
Eivind

Reputation: 72

To move the fill rect in the background layer of the plot, you can specify the layer parameter of the add_vrect() method to be 'below' like this:

fig.add_vrect(x0=0, x1=np.pi, line_width=0, fillcolor="pink", layer="below")

This will move the fill rect to the background layer and you will be able to see the data points on top of it. You can also use the add_shape() method to add a rectangle shape to the background layer and specify the fillcolor and other properties as needed.

fig.add_shape(
        type="rect",
        x0=0,
        y0=0,
        x1=np.pi,
        y1=1,
        fillcolor="pink",
        line_width=0,
        layer="below"
    )

This will add a rectangle shape to the background layer of the plot with the specified dimensions and properties.

Upvotes: 1

Related Questions