Zero
Zero

Reputation: 1899

How to change the legend names in a plotly bar graph in Python

I have a bar graph that looks like this -

enter image description here

As you can see the legend shows 0 and 1. I want to change this to show "Didn't Survive" and "Survived". For this I tried adding the code below in the px.histogram function but it didn't change the output -

labels = {0:"Didn't Survive", 1:"Survived"}

My original code is similar to this -

survivor = px.histogram(data_frame = train_df, x = "Survived", title = "Survivor Data")
survivor.update_layout(bargap = 0.6)

I am working on the Titanic dataset.

Upvotes: 0

Views: 1816

Answers (1)

Drakax
Drakax

Reputation: 1493

Legends for px.histogram (color="", actually) are auto-generated from your data.

I guess in your df 0 = dead and 1 = survived, or the opposite.

So you have 2 solution:

  1. You completely rename/replace values in your original df

or

  1. You "hack/trick" px with a new fake column which will be a copy of the one you want to use the column name and values for the legend title and legend labels:

For example, let's take a generic plot:

import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill", color="time")
fig.show()

Click the pic to zoom in enter image description here

You see, because I set color="" on the column "time", I get its name/values for legend title/lables = time:dinner:lunch.

Because the df look like this:

index total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3

...

index total_bill tip sex smoker day time size
86 13.03 2.0 Male No Thur Lunch 2
87 18.28 4.0 Male No Thur Lunch 2

So what I do, it's copying the desired column form original df into a new column, then replace all the data, so for my df it will:

df['test'] = df['time']
df['test'] = df['test'].replace({'Dinner': 'Test1', 'Lunch': 'Test2'})
df
index total_bill tip sex smoker day time size test
0 16.99 1.01 Female No Sun Dinner 2 Test1
1 10.34 1.66 Male No Sun Dinner 3 Test1

...

index total_bill tip sex smoker day time size test
86 13.03 2.0 Male No Thur Lunch 2 Test2
87 18.28 4.0 Male No Thur Lunch 2 Test2

AND NOW if I generate my plot again this is what it shows:

import plotly.express as px
fig = px.histogram(df, x="total_bill", color="test")
fig.show()

And voilà! (click on it to zoom...) enter image description here

Note:

This is the trick I'm using, if you find something official, let me know because I didn't find anything :)

Long explanation but 2 lines of code actually ;)

Upvotes: 1

Related Questions