将分组条形图中每个条形的颜色更改为自定义颜色
Posted
技术标签:
【中文标题】将分组条形图中每个条形的颜色更改为自定义颜色【英文标题】:Change color of each bar in a grouped bar chart plotly to custom colors 【发布时间】:2021-09-24 22:07:43 【问题描述】:我正在尝试为绘图图表中的每个条形使用自定义十六进制代码,但我无法解决这个问题。
谁能帮帮我。
下面是我使用的代码
#Defining Custom Colors
colours = 'Base_Models': '#0C3B5D',
'Standard_scaled_scores': '#3EC1CD',
'Min_Max_scaled_scores': '#EF3A4C',
'Scaling & feature selection_scores': '#FCB94D'
import plotly.express as px
fig = px.bar(compareModels_aft_Cleansing, x="Base_Models", y=["Base_Models_Scores",
"Standard_scaled_scores", "Min_Max_scaled_scores",
"Scaling & feature selection_scores"],
title="Training Scores", barmode='group', text = 'value',
hover_name="Base_Models",
hover_data='Base_Models':False, # remove species from hover data
color = colours)
【问题讨论】:
【参考方案1】: 你没有提供样本数据所以我合成了 据我了解,您的 colors 地图不正确。您将 Base_Models_Scores 绘制为条形而不是 Base_Models,这是 x 轴 您需要的参数是color_discrete_map来实现您的要求import pandas as pd
import numpy as np
# Defining Custom Colors
colours =
"Base_Models_Scores": "#0C3B5D",
"Standard_scaled_scores": "#3EC1CD",
"Min_Max_scaled_scores": "#EF3A4C",
"Scaling & feature selection_scores": "#FCB94D",
# generate sample data...
compareModels_aft_Cleansing = pd.DataFrame(
**"Base_Models": colours.keys(),
**
c: np.random.randint(1, 4, len(colours.keys()))
for c in colours.keys()
,
)
import plotly.express as px
fig = px.bar(
compareModels_aft_Cleansing,
x="Base_Models",
y=[
"Base_Models_Scores",
"Standard_scaled_scores",
"Min_Max_scaled_scores",
"Scaling & feature selection_scores",
],
title="Training Scores",
barmode="group",
text="value",
hover_name="Base_Models",
hover_data="Base_Models": False, # remove species from hover data
color_discrete_map=colours,
)
fig
【讨论】:
以上是关于将分组条形图中每个条形的颜色更改为自定义颜色的主要内容,如果未能解决你的问题,请参考以下文章