'How to make legend items bold in plotly

I am able to bold the axis title and ticks using update_xaxes,but is there a way to do the same for the items in the legend?

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Automatic Labels Based on Data Frame Column Names")

fig.update_xaxes(tickprefix="<b>",ticksuffix ="</b><br>",title_text= "<b> sepal_length </b>" )
fig.show()


Solution 1:[1]

You can use a lambda function and some basic html formatting with:

fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>'))

And get:

enter image description here

If you'd like to highlight one or some of the legend entries you can sprinkle the previous statement with:

bold = 'versicolor'
fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>') if t.name in bold else())

And get:

enter image description here

Complete code:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Automatic Labels Based on Data Frame Column Names")

# Plot 1
# fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>'))

# Plot 2
bold = 'versicolor'
fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>') if t.name in bold else())

fig.show()

Solution 2:[2]

I don't know if exists a way to make a entire legend (with values) bold, but you can set label with labels kwarg on px.scatter method, and then add some html to make it bold.

import plotly.express as px

df = px.data.iris()
fig = px.scatter(
    df, 
    x="sepal_length", 
    y="sepal_width", 
    color="species",
    title="Automatic Labels Based on Data Frame Column Names",
    labels={
      "species": "<b>Species</b>" # here :)
    })

fig.show()

Solution 3:[3]

For those who use plotly.graph_objs, add <b> </b> to trace 'name' :

Example:

import plotly.graph_objs as go

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y,name=f"<b>Text</b>"))
           

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dharman
Solution 3 basil_man