我有个情节:

下面是情节代码:
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')我已经试过很多次了,但是颜色仍然没有改变,也没有改变。
发布于 2022-04-13 17:48:06
在使用color="target" Plotly创建图形时,您错过了
全工作代码
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,
)https://stackoverflow.com/questions/71859677
复制相似问题