Search code examples
pythonplotlyvisualizationscatter-plot

Cant manage to format or remove legend in px.scatter


I am trying to move the legend of a scatter plot a bit, but nothing seems to work.

this is the simple scatter plot.

fig_party_body = px.scatter(body_data, x= 'mean_stance', y = 'interest', color = 'mean_stance' )
fig_party_body

this is the scatter result: enter image description here

now i want to move the legend, but i cant manage to do it with update layout - for example, this code doesnt budge it at all no matter what i do (switch xanchor, fiddle with the x and y values):

fig_party_body.update_layout(
    legend=dict(
        x=1.02,  # Adjust the x position of the legend
        y=1.0,  # Adjust the y position of the legend
        borderwidth=2,  # Set legend border width
        xanchor='right',  # Set x anchor to the right side of legend
        yanchor='top'  # Set y anchor to the top of legend
    ))

even trying to remove it completely, with update_layout(showlegend = False) doesnt work! its still there. what am i doing wrong? this is important for other, more intricate graphs i am building. thank you!


Solution

  • Is it the color bar without the legend that you want to move on the question? Then the setting is colorbar with colorscale.

    import plotly.express as px
    
    df = px.data.iris()
    fig = px.scatter(df, x="sepal_width", y="sepal_length", color='petal_length')
    
    fig.update_layout(
        coloraxis=dict(colorbar=dict(
            x=1.02,  # Adjust the x position of the legend
            y=1.0,  # Adjust the y position of the legend
            borderwidth=2,  # Set legend border width
            xanchor='right',  # Set x anchor to the right side of legend
            yanchor='top'  # Set y anchor to the top of legend
        ))
    )
    
    fig.show()
    

    enter image description here