How to customize legend of Bubble chart

Hi,
I’m trying to make a custum legend, this what I’m trying to do :

here’s the code :

import plotly.graph_objects as go
import plotly.express as px 
import pandas as pd


data = {'x': [1.5, 1.6, -1.2],
        'y': [21, -16, 46],
        'circle-size': [10, 5, 6],
        'circle-color': ["red","red","green"],
        'tttt': ["ggg","vvvv","rrrr"],
        
        }

# Create DataFrame
df = pd.DataFrame(data)
fig = px.scatter(
    df,
    x="x", 
    y="y", 
    color="circle-color",
    size='circle-size',
    hover_name="tttt",
    color_discrete_map={"red": "red", "green": "green"}
)



fig.show()

the result :

so now I want to customize the part which I circled in red…I want to display something like this :

is it possible please ?
thanks

:wave: Hi! You know, that at first sight this question seem to be answered just by reading the documentation, however when I was looking for it, I couldn’t find it right away, so :thinking:

The key thing here, I guess, is that when using plotly.graph_objects you can choose the name of your trace as you wish…
Manual Labelling with Graph Objects … but that it’s not the case…

So… I kept looking, and as always, there is sht posted on Stackoverflow… :bulb:
change-variable-label-names-for-the-legend

And :tada: there you go!
I think you have to figure out how the figure is structured, so you can change any parameter or at least where to find it in a way that allows you to modify it. Here is the fig.update() method use to change the traces names:
https://plotly.com/python-api-reference/generated/plotly.graph_objects.Figure.html?highlight=update#plotly.graph_objects.Figure.update

Code here
import plotly.express as px 
import pandas as pd


data = {'x': [1.5, 1.6, -1.2],
        'y': [21, -16, 46],
        'circle-size': [10, 5, 6],
        'circle-color': ["red","red","green"],
        'tttt': ["ggg","vvvv","rrrr"],
        
        }

# Create DataFrame
df = pd.DataFrame(data)
fig = px.scatter(
    df,
    x="x", 
    y="y", 
    color="circle-color",
    size='circle-size',
    hover_name="tttt",
    color_discrete_map={"red": "red", "green": "green"}
)



# fig.show()
newnames = {'red':'hello', 'green': 'hi'}
fig.for_each_trace(lambda t: t.update(name = newnames[t.name],
                                      legendgroup = newnames[t.name],
                                      hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])
                                     )
                  )
fig

@JuanG thanks for your time and effort…but this is not what i’m looking for .
first I need to change the possition to the top the of the graph like this :

:slightly_smiling_face: Now… I think that here it’s what your looking for…
https://plotly.com/python/legend/#horizontal-legends

1 Like

many thanks :slight_smile:

@JuanG …one more question please…when I applied the update function to my code I got this error :

the code :

import plotly.express as px 
import pandas as pd


data = {'x': [1.5, 1.6, -1.2],
        'y': [21, -16, 46],
        'circle-size': [10, 5, 6],
        'circle-color': ["red","red","green"],
        'tttt': ["ggg","vvvv","rrrr"],
        
        }

# Create DataFrame
df = pd.DataFrame(data)
fig = px.scatter(
    df,
    x="x", 
    y="y", 
    color="circle-color",
    size='circle-size',
    hover_name="tttt",
    color_discrete_map={"red": "red", "green": "green"}
) 
fig.update_layout(
        {
            
            'yaxis': {
                "range": [-100, 100],
                'zerolinewidth': 2, 
                "zerolinecolor": "red",
                "tick0": -100,
                "dtick": 25,
            },
            'xaxis': {
                "range": [-100, 100],
                'zerolinewidth': 20, 
                "zerolinecolor": "black",
                "tick0": -100,
                "dtick": 25,
                #  "scaleanchor": 'y'
            },
           
            "height": 800
        }
    )
fig.update_traces(textposition='middle right', textfont_size=14, textfont_color='black', textfont_family="Inter", hoverinfo="skip", hovertemplate=None, hoverlabel_bgcolor="white", hoverlabel_font_color="black", hoverlabel_font_family="Inter", hoverlabel_font_size=12)
fig.add_scatter(
        x=[0, 0, -100, -100],
        y=[0, 100, 100, 0],
        fill="toself",
        fillcolor="rgba(37, 227, 95, 0.5)",
        zorder=-1,
        mode="markers",
        marker_color="rgba(0,0,0,0)",
        showlegend=False,
        hoverinfo="skip"
    )

     


newnames = {'red':'hi', 'green': 'hello'}
fig.for_each_trace(lambda t: t.update(name = newnames[t.name],
                                        legendgroup = newnames[t.name],
                                        hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])
                                        )
                        )

fig

error :

line 65, in 
    hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])
                    ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'replace'

is it normal ?

Yes… I have no error, but hovertemplate is wrong…
I haven’t gone deeper, but if you would need the hover property, I think you have to tweak hover_name.
https://plotly.com/python/hover-text-and-formatting/

Go for it and let me know how it was! And also show me the final figure, please!! I’d like to bookmark this kind of questions for further check out!

1 Like