'Color do not change using color_discrete_map
I have this plot:
Here is code of plot:
plot_df = pd.DataFrame(df.groupby('target')['age'].mean())
plot_df = plot_df.reset_index()
fig = px.bar(plot_df, x='target', y='age',height=800,
title='Average Age by Target',
color_discrete_map={'Finance & Investments': '#BFC5DA','Manufacturing': '#5D6A92'},
text='age', opacity=0.85)
fig.update_traces(texttemplate='Mean age %{text:,0.f}',
textposition='outside',
marker_line=dict(width=1, color='#303030'))
fig.update_xaxes(title="Industry")
fig.update_yaxes(title="Mean Age")
fig.update_layout(paper_bgcolor='#F4F2F0',
plot_bgcolor='#F4F2F0',
title_font_size=28, font_family="monospace",
width=1300,
height=700,
showlegend=False)
fig.show(renderer='colab')
I have tried many times but color still remains the same and does not change
Solution 1:[1]
You missed color="target"
in creating the figure with Plotly Express
full working code
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame(
{
"target": np.random.choice(
["Finance & Investments", "Manufacturing", "Technology"], 100
),
"age": np.random.uniform(15, 55),
}
)
plot_df = pd.DataFrame(df.groupby("target")["age"].mean())
plot_df = plot_df.reset_index()
fig = px.bar(
plot_df,
x="target",
y="age",
height=800,
title="Average Age by Target",
color="target", # this parameter was missed !!!
color_discrete_map={"Finance & Investments": "#BFC5DA", "Manufacturing": "#5D6A92"},
text="age",
opacity=0.85,
)
fig.update_traces(
texttemplate="Mean age %{text:,0.f}",
textposition="outside",
marker_line=dict(width=1, color="#303030"),
)
fig.update_xaxes(title="Industry")
fig.update_yaxes(title="Mean Age")
fig.update_layout(
paper_bgcolor="#F4F2F0",
plot_bgcolor="#F4F2F0",
title_font_size=28,
font_family="monospace",
width=1300,
height=700,
showlegend=False,
)
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 | Rob Raymond |