在每个标签的堆积条形图中设置颜色 [英] Set colors in stacked bar plot per label

查看:107
本文介绍了在每个标签的堆积条形图中设置颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置每次运行此barplot时都会弹出的相同颜色.例如:B1 =绿色,B2,红色,B3 =蓝色等

I want to set the same colors pop up each time I run this barplot. For example: B1 = green, B2, red, B3 = blue etc.

到目前为止,我已经尝试过.setcolor,但是它没有为我设置单个框号(B1,B2等)的颜色-我无法弄清楚.

I have so far tried .setcolor but it does not provide me to set the colors for individual box numbers (B1, B2 etc) -- I could not figure it out.

import pandas as pd
import seaborn as sns


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)

sns.set()
data1.set_index('DAY').plot(kind='bar', stacked=True)

这有效,但是一旦我有新数据,它就会为B1,B2,B3等分配不同的颜色.

This works, but it assigns different colors for B1, B2, B3 etc. once I have new data..

例如,让我们给它一些玩具数据:

For example, let us give it some toy data:

t = {'DAY': [55,56,58,65], 'B1': [2,6,6,1],  'B3': [0,1,0,1]}
toy1= pd.DataFrame(data = t)
sns.set()
toy1.set_index('DAY').plot(kind='bar', stacked=True)

B3在这里是橙色,而第一个是绿色.

B3 is orange here, whereas it was green in the first one.

推荐答案

创建一个词典并将这些列映射到这些颜色.由于我们在列上进行迭代,因此颜色的绘制顺序与列的绘制顺序相同.您将需要为所有不同的列定义颜色.

Create a dictionary and map the columns to those colors. Because we iterate over the columns, the colors will be in the same order the columns are plotted. You will need to define colors for all of your different columns.

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))

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

但是,这不能确保顺序一致.也就是说,如果您的DataFrame的订购顺序不同,尽管B3始终是相同的颜色,但堆叠时它可能会高于B1或低于B1.一个更一致的解决方案是重新索引.您必须包括在所有需要一致绘制的数据框中找到的全部 Bi.在这里,我选择了任意数量的1-9:

This, however, does not ensure that the ordering is consistent. That is, if your DataFrame is ordered differently, though B3 will always be the same color, it may wind up being above or below B1 when stacked. A more consistent solution is to reindex. You must include all Bi that are found across all of your DataFrames that need to be plotted consistently. Here I chose an arbitrarily large number of 1-9:

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

toy1 = toy1.reindex(['DAY'] + [f'B{i}' for i in range(1,10)], axis=1)
toy1.set_index('DAY').plot(kind='bar', stacked=True)

虽然B3首先出现在DataFrame中,但它仍然绘制在B1上方,并在循环中显示第三种颜色.

Though B3 appears first in the DataFrame, it was still plotted above B1, and with the third color in the cycle.

这篇关于在每个标签的堆积条形图中设置颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆