Search code examples
pythonplotlybar-chartlegendplotly-express

Plotly: How to rename legend elements of a plotly express stacked bar plot?


I use this example code given in plotly website.

import plotly.express as px
long_df = px.data.medals_long()
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
fig.show()

This gives a plot like below.

enter image description here

How can I rename the legends to replace gold, silver and bronze with first, second and third?


Solution

  • map the data to the values you want

    import plotly.express as px
    long_df = px.data.medals_long()
    fig = px.bar(long_df, x="nation", y="count", 
                 color=long_df["medal"].map({"gold":"first","silver":"second","bronze":"third"}), 
                 title="Long-Form Input")
    fig.show()