Search code examples
pythonpandasplotlyvisualizationplotly-express

How to change the legend / label names on the pie chart in plotly express


Shown below is the syntax used to change the legend / label names on plotly express

fig = px.pie(df,
             values = "Total",
             names = 'index',
             hole = 0.5,
             color_discrete_sequence = ['#2C3E50','#CACFD2'],
             labels = {1:'yes', 2:'no'} )
        
fig.update_traces(textinfo='value + percent')
fig.show()

However, the label names does not change as it shows as below

enter image description here

How can I change the legend / label names on the pie chart in plotly express as 1 should be "Yes" and 2 should be "No".


Solution

  • Change the names of the values on index with map and then plot it:

    labels = {1:'yes', 2:'no'}
    df['index'] = df['index'].map(labels)
    fig = px.pie(...)