根据SEMI已知标签在堆叠条形图中设置颜色

时间:2019-05-20 20:37:14

标签: python dictionary matplotlib seaborn

我问了一个类似的问题,在此之前回答得很完美。

Set colors in stacked bar plot per label

def gen_colors(df):
    col_d = {'B1': 'red', 'B2': 'black', 'B3': 'green'}
    return [col_d[col] for col in df.columns if 'B' in col]


sns.set()

d = {'DAY': [55,56,58,65], 'B1': [2,6,6,1],  'B2': [1,0,21,0], 'B3': [0,1,0,1]}
data1 = pd.DataFrame(data = d)
data1.set_index('DAY').plot(kind='bar', stacked=True, color=gen_colors(data1))

works

例如,现在我以此为基础,如果我们不知道标签扩展名怎么办。 (无法事先知道标签扩展名,它们会带有B1_Active,B2_Missing,B3_Double之类的名称。(B *之后的名称称为包装盒的状态)

def gen_colors(df):
    col_d = {'B1': 'red','B1_Missing': 'firebrick', 'B2': 'black', 'B3': 'green'}
    return [col_d[col] for col in df.columns if 'B' in col]

t = {'DAY': [55,56,58,65], 'B1_Active': [2,6,6,1],  'B3_Missing': [0,1,0,1]}
    toy1 = pd.DataFrame(data = t)

    try:
        toy1.set_index('DAY').plot(kind='bar', stacked=True, color=gen_colors(toy1))
    except:
        toy1.set_index('DAY').plot(kind='bar', stacked=True)

这只是导致颜色随机选择。当标签以B1开头时,如何制作字典以给出不同深浅的红色,例如B1_Active =红色,B1_Missing =耐火砖等。我的意思是我想使B1的所有组合的主色保持相同,但要添加略带阴影以区别状态。这可能吗?我搜索了“全部捕获”字典,但无法使用正则表达式。.谢谢

enter image description here

这也是调色板:

enter image description here

1 个答案:

答案 0 :(得分:0)

您的标签扩展名的格式为B {number} _ {status}。考虑我们称它们为labex。正则表达式库中的split函数使您可以将状态与其余状态分开。例如

null

现在,我将考虑您知道有多少B和身份可能性。您可以简单地使用defaultdict(从集合中导入)根据B值存储颜色,并使用列表存储每个状态的索引。

.htaccess

这应该为您提供一个起点。状态值不必事先知道,因为您可以简单地将状态初始化为'[]',并在遇到它们时将新值附加到其上。相同的逻辑适用于B值,但是您需要在内存中的任何一种方式中存储所存储的色度,或者需要能够即时生成它们。