Python中基于标签名称的固定配色条形图实现求助
固定条形图标签与颜色的配对方法
作为Python新手,处理电子表格时通过字符串过滤生成多个条形图,需要确保每个标签对应固定颜色(如Effective=绿色、Not Effective=红色、Not Applicable=灰色、No Visibility=橙色),但不是所有标签都会出现在每个图里,不能靠顺序分配颜色,需要指定配对关系。
现有代码与数据
读取并过滤数据的代码:
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns filtered_audit_result_columns = pd.read_csv('audit_results.csv', usecols=["Title", "Implementation Status"]) guidelines_for_data_centre = filtered_audit_result_columns[filtered_audit_result_columns['Title'].str.contains('Guidelines for Data Centres')]
过滤后的数据:
Title Implementation Status 0 Guidelines for Data Centres Effective 1 Guidelines for Data Centres Not Effective 2 Guidelines for Data Centres Not Effective 3 Guidelines for Data Centres Not Effective 4 Guidelines for Data Centres Effective 5 Guidelines for Data Centres Not Applicable 6 Guidelines for Data Centres Effective 7 Guidelines for Data Centres Not Effective 8 Guidelines for Data Centres No Visibility 9 Guidelines for Data Centres No Visibility 10 Guidelines for Data Centres Not Applicable 11 Guidelines for Data Centres No Visibility 12 Guidelines for Data Centres Effective 13 Guidelines for Data Centres Not Applicable
统计标签数量的代码:
count = guidelines_for_data_centre['Implementation Status'].value_counts()
统计结果:
Not Effective 4 Not Applicable 3 Effective 4 No Visibility 3
原绘图代码:
hbar = count.plot.barh(x= 'Implementation Status')
解决方案:用颜色映射字典固定配对
步骤1:定义标签-颜色的固定映射
先创建一个字典,把所有可能出现的标签和对应的颜色一一绑定,相当于一个"颜色对照表":
# 自定义标签与颜色的映射,支持英文颜色名或十六进制色码 color_map = { 'Effective': 'green', 'Not Effective': 'red', 'Not Applicable': 'gray', 'No Visibility': 'orange' }
步骤2:为当前统计结果匹配颜色
遍历当前统计结果的索引(也就是当前图里存在的标签),从颜色字典中取出对应颜色,组成专属颜色列表:
# 生成当前条形图需要的颜色列表 bar_colors = [color_map[label] for label in count.index]
步骤3:绘制带固定颜色的条形图
调用绘图方法时,通过color参数传入刚才生成的颜色列表:
# 绘制水平条形图并应用固定颜色 hbar = count.plot.barh(color=bar_colors) plt.show() # 必须添加这句,否则图形可能无法显示
完整整合代码
把所有步骤整合在一起,直接运行即可:
import pandas as pd import matplotlib.pyplot as plt # 读取并过滤数据 filtered_audit_result_columns = pd.read_csv('audit_results.csv', usecols=["Title", "Implementation Status"]) guidelines_for_data_centre = filtered_audit_result_columns[filtered_audit_result_columns['Title'].str.contains('Guidelines for Data Centres')] # 统计标签数量 count = guidelines_for_data_centre['Implementation Status'].value_counts() # 定义标签-颜色映射 color_map = { 'Effective': 'green', 'Not Effective': 'red', 'Not Applicable': 'gray', 'No Visibility': 'orange' } # 匹配对应颜色 bar_colors = [color_map[label] for label in count.index] # 绘制带固定颜色的条形图 hbar = count.plot.barh(color=bar_colors) plt.show()
补充说明
- 后续如果新增标签,只需在
color_map里添加新的键值对(比如'New Status': 'blue'),所有图表都会自动适配对应颜色。 - 颜色值可以用易懂的英文名称(如
'green'),也可以用更精准的十六进制码(如'#2ecc71'),根据需求调整即可。
内容的提问来源于stack exchange,提问作者adam
相关产品推荐
相关产品推荐

