python-3.x - 根据列值指定直方图的颜色。跨图表一致
问题描述
我正在尝试使用 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] ,其颜色的十六进制值对应于状态。但这也不起作用。
有人可以告诉我我缺少什么以及如何使它正常工作吗?
解决方案
要将相同的颜色映射到相同的值,您将对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'
}
)
推荐阅读
- java - 是否可以在 Apache Kafka Java 客户端中禁用 SSL 证书验证?
- python - 根据开始和结束时间剪切波形格式的音频文件
- c# - C#如何将两个数据表的值与容差进行比较
- halide - Halide:如何避免 Halide LUT 索引中不必要的执行开销
- java - 包 java.util.logging 在 Java 中不可访问
- javascript - React Js无法从API中删除记录
- sql - 我想知道是否有一种优雅的方法可以在 Google 表格中应用查询、数组公式、排序、函数的组合来执行以下操作
- c# - .net core 3.1 with Npgsql EF Core - 不能用处理程序类型 Int32Handler 编写 CLR 类型枚举
- postsharp - Nlog 直接访问工作但不是 PostSharp 默认
- php - 如何直接将缅甸 Unicode 数据打印到 pos 网络打印机?