Python Seaborn - 根据色调名称更改条形颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46173419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:31:15  来源:igfitidea点击:

Seaborn - change bar colour according to hue name

pythonseaborn

提问by asongtoruin

I'm using seabornand pandasto create some bar plots from different (but related) data. The two datasets share a common category used as a hue, and as such I would like to ensure that in the two graphs the bar colour for this category matches. How can I go about this?

我正在使用seabornpandas从不同(但相关)的数据创建一些条形图。这两个数据集共享一个用作 a 的公共类别hue,因此我想确保在这两个图中,该类别的条形颜色匹配。我该怎么办?

A basic example is as follows:

一个基本的例子如下:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_style('darkgrid')
fig, ax = plt.subplots()

a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})

g = sns.barplot(data=a, x='Scenario', y='Duration',
                hue='Program', ci=None)
plt.tight_layout()
plt.savefig('3 progs.png')

plt.clf()

b = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'C', 'C', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 3, 2, 12, 9]})

g = sns.barplot(data=b, x='Scenario', y='Duration',
                hue='Program', ci=None)
plt.tight_layout()
plt.savefig('4 progs.png')

Producing the two graphs: 3 category bar plot4 category bar plot

生成两个图: 3类条形图4类条形图

In this example, I would like to ensure that the Totalcategory uses the same colour in both graphs (e.g. black)

在这个例子中,我想确保Total类别在两个图中使用相同的颜色(例如黑色)

回答by ImportanceOfBeingErnest

A. using a list of colors

A. 使用颜色列表

The easiest solution to make sure to have the same colors for the same categories in both plots would be to manually specify the colors at plot creation.

确保两个图中相同类别具有相同颜色的最简单解决方案是在创建图时手动指定颜色。

# First bar plot
ax = sns.barplot(data=a, x='Scenario', y='Duration',
                hue='Program', ci=None, palette=["C0", "C1", "k"])

# ...
# Second bar plot
ax2 = sns.barplot(data=b, x='Scenario', y='Duration',
                hue='Program', ci=None,  palette=["C0", "C1","C2", "k"])

The color "C2"(the third color of the color cycle) is only present in the second plot where there exists a Programm C.

颜色"C2"(颜色循环的第三种颜色)仅出现在存在程序 C 的第二个图中。

B. using a dictionary

B. 使用字典

Instead of a list, you may also use a dictionary, mapping values from the huecolumn to colors.

除了列表,您还可以使用字典,将hue列中的值映射到颜色。

palette ={"A":"C0","B":"C1","C":"C2", "Total":"k"}

ax = sns.barplot(data=a, x='Scenario', y='Duration', hue='Program', palette=palette)
# ...
ax2 = sns.barplot(data=b, x='Scenario', y='Duration', hue='Program', palette=palette)

In both cases, the output would look like this:
enter image description here

在这两种情况下,输出将如下所示:
在此处输入图片说明

C. automatic dictionary

C.自动词典

Finally, you may create this dictionary automatically from the values from the huecolumn. The advantage here would be that you neither need to know the colors, nor the values in the respective dataframes beforehands.

最后,您可以根据hue列中的值自动创建此字典。这里的优点是您既不需要事先知道颜色,也不需要知道相应数据框中的值。

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_style('darkgrid')
fig, ax = plt.subplots()

a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})
b = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'C', 'C', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 3, 2, 12, 9]})

unique = a["Program"].append(b["Program"]).unique()
palette = dict(zip(unique, sns.color_palette()))
palette.update({"Total":"k"})

ax = sns.barplot(data=a, x='Scenario', y='Duration',
                hue='Program', ci=None, palette=palette)
plt.tight_layout()
plt.figure()

ax2 = sns.barplot(data=b, x='Scenario', y='Duration',
                hue='Program', ci=None,  palette=palette)
plt.tight_layout()
plt.show()