Black Lives Matter. Please consider donating to Campaign Zero's mission of ending police violence in America.
https://www.joincampaignzero.org

Changing label of plotly express facet categories

Hi,

When creating a chart with Plotly Express and using either legend by color or a facet, the names of the facets or legends show the variable as well as the value, e.g. in the example below, “day=Thur” or "smoker=“Yes”

If I want them just to say “Thur” or “Yes” in those examples, what’s the easiest way to do that?

Thanks,
Andrew

1 Like

I’m also curious about this.

Anyone found a solution to fix legends?

Here’s a little pattern you can use, although it may break in a future version of plotly when we add legend titles:

import plotly.express as px

tips = px.data.tips()
fig = px.scatter(tips, x="total_bill", y="tip", facet_row="time", facet_col="day", color="smoker")
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[1]))
fig.for_each_trace(lambda t: t.update(name=t.name.split("=")[1]))
fig.show()

This version will be more future-friendly in case PX ever stops using this A=B pattern:

import plotly.express as px

tips = px.data.tips()
fig = px.scatter(tips, x="total_bill", y="tip", facet_row="time", facet_col="day", color="smoker")
fig.for_each_annotation(lambda a: a.update(text=a.text.replace("day=", "")))
fig.for_each_annotation(lambda a: a.update(text=a.text.replace("time=", "")))
fig.for_each_trace(lambda t: t.update(name=t.name.replace("smoker=", "")))
fig.show()
1 Like

A related but different question, how do I access individual trace of plotly express facet? Say I only want to update the first trace instead of other trace. Thank you!

Is there a for_each_layout? Eg. I want to add annotations on subplots generated by facet but I couldn’t find a way to do that. Basically I want to do

fig.update(layout=dict(annotations=[go.layout.Annotation(
                    text="*", yref="paper", x=marker, y=1, showarrow=False) for marker in significant_list]))

This isn’t feasible if fig is generated by plotly.express with facet because there would be multiple subplots. Is there a way to identify each subplots and then modify the layout, which is adding annotation on the plots?

Thank you so much!

You can ‘target’ annotations by row/col with add_annotation just like add_trace:

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", facet_col="smoker")
fig.add_annotation(row=1,col=1, x=10, y=6, text="hi", arrowhead=1)

1 Like

Unfortunately, though, this overrides yref at the moment so it might not help you :frowning:

Thank you so much for answering my question. It would be nice to see yref=“paper” enabled for subplots. Thank you!