Plotly python 直方图将自定义颜色添加到不同的值

Plotly python histogram add custom colors to distinct values

我有一个数据框,一列中有 4 个不同的值,我需要为每个值设置自定义颜色。

下面是示例数据

val,cluster
118910.000000,3
71209.000000,2
25674.666667,0
109267.666667,3
8.000000,1

下面是代码。

fig = px.histogram(types, x="val",color='cluster')
fig.show()

类型是来自给定数据的数据帧名称

当我想我得到了默认颜色。相反,我需要得到

0:红色

2:蓝色

1:紫色

3:绿色

如何在 python 中为直方图

设置自定义颜色

谁能帮忙解决这个问题

您可以使用 color_discrete_map.

import pandas as pd 
import random
df = pd.DataFrame([[random.random()*100,random.randint(0,3)]for i in range (100)],columns = ['val','cluster'])
fig = px.histogram(df, x="cluster",y='val',
                   color = 'cluster',
                    color_discrete_map = {0:'red',1:'blue',2:'purple',3:'green'}
                  )
fig