首页 > 解决方案 > 根据列值指定直方图的颜色。跨图表一致

问题描述

我正在尝试使用 plotly express 绘制直方图。我有一个数据框,其值如下:

    env     type    status  success count
0   PROD    ABC     403     False   21
1   IMPL    HTTP    200     True    64037
2   IMPL    HTTP    304     False   9
3   PROD    ABC     503     False   1
4   IMPL    ABC     200     True    3308
5   PROD    HTTP    204     True    54
6   IMPL    ABC     500     False   1000
7   PROD    ABC     500     False   100
....          .....       ....

我想根据各种分组(env,type)绘制多个图表(直方图或饼图),显示每个分组中错误代码的总数。我正在尝试类似的东西:

fig = px.pie(df.groupby("success").get_group(False), title="Overall Failure Count", names="status", values = "count", color='status')
fig.show()

for env, df_env in df.groupby("env"):
    fig = px.pie(df_env.groupby("success").get_group(False), title="Failure Count for %s"%env, 
          names="status", values = "count", color='status')
    fig.show()

有了这个,状态的颜色是动态生成的,并且对于跨图表的相同状态是不同的。我想要为所有图表生成的颜色,以便它们在不同的图表中保持一致。

例如:状态代码 200 的颜色在所有图表中为红色

我尝试使用 dict() 将状态映射到颜色:

def colors(n):
    color_list = list()
    for i in range(n):
        random_number = random.randint(0,16777215)
        hex_number = str(hex(random_number))
        hex_number ='#'+ hex_number[2:]
        color_list.append(hex_number)
    return color_list
statuses = list(df.status.unique())
colors_list = colors(len(statuses))
colorMap = dict(zip(statuses, colors_list))

fig = px.pie(df.groupby("success").get_group(False), title="Overall Failure Count", names="status", values = "count", color=df['status'].apply(lambda x : colorMap[x]))

但我收到以下错误:

All arguments should have the same length. The length of argument `color` is 14, whereas the length of previous arguments ['status', 'count'] is 24

我还尝试了其他各种方法,例如创建一个列 df['color] ,其颜色的十六进制值对应于状态。但这也不起作用。

有人可以告诉我我缺少什么以及如何使它正常工作吗?

标签: python-3.xjupyter-notebookplotly

解决方案


要将相同的颜色映射到相同的值,您将对color_discrete_map所有绘图使用相同的选项,请参阅使用离散颜色的显式映射直接将颜色映射到数据值

在你的情况下,是这样的:

fig = px.pie(df.groupby("success").get_group(False), 
             title="Overall Failure Count", 
             names="status", 
             values="count", 
             color='status',
             color_discrete_map={200:'red',
                                 403:'blue',
                                 304:'green',
                                 503:'yellow',
                                 204:'grey',
                                 500:'cyan'
                                }
            )

推荐阅读