【问题标题】:Set custom seaborn color palette using hex codes, and name the colors使用十六进制代码设置自定义 seaborn 调色板,并命名颜色
【发布时间】:2018-10-04 17:18:52
【问题描述】:

我的公司有一个正式的调色板,所以我需要在我的 seaborn 图表中使用这些颜色。因此,我想设置默认的 seaborn 调色板,并为这些颜色提供易于使用的名称,例如“p”代表紫色,“g”代表绿色。

这是我目前的代码:

# Required libraries
import matplotlib.pyplot as plt
import seaborn as sns

# Wanted palette details
enmax_palette = ["#808282", "#C2CD23", "#918BC3"]
color_codes_wanted = ['grey', 'green', 'purple']

# Set the palette
sns.set_palette(palette=enmax_palette)

# Assign simple color codes to the palette

请帮助我使用我的“color_codes_wanted”列表为颜色分配简单的名称。

【问题讨论】:

  • 我不认为我完全理解这个问题。您可以定义一个函数c = lambda x: enmax_palette[color_codes_wanted.index(x)] 并在代码的其余部分使用c("grey")。这就是你所追求的吗?
  • 有趣的解决方案。是的,您的回答将适用于我的目的。我认为可能有一种内置的方式来做到这一点(即在默认调色板中为十六进制代码分配简单的颜色名称)。谢谢!
  • 我的意思是,你可以做很多事情。您想在哪些用例中使用这些颜色?
  • 例如g = sns.distplot(x, color='official_company_green'),颜色为我公司官方的绿色。就像可以使用默认的 seaborn 颜色一样:g = sns.distplot(x, color='b')

标签: python matplotlib seaborn


【解决方案1】:

使用自定义函数

如评论所述,您可以创建一个函数,如果使用自定义颜色名称调用该函数,则返回列表中的十六进制颜色。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Wanted palette details
enmax_palette = ["#808282", "#C2CD23", "#918BC3"]
color_codes_wanted = ['grey', 'green', 'purple']

c = lambda x: enmax_palette[color_codes_wanted.index(x)]

x=np.random.randn(100)
g = sns.distplot(x, color=c("green"))

plt.show()

使用 C{n} 表示法。

需要注意的是seaborn中所有的颜色都是matplotlib的颜色。 matplotlib 提供的一个选项是所谓的 C{n} 表示法(n = 0..9)。通过指定像 "C1" 这样的字符串,您可以告诉 matplotlib 使用当前颜色循环中的第二种颜色。 sns.set_palette 将颜色循环设置为您的自定义颜色。因此,如果您能记住它们在循环中的顺序,您可以使用此信息并指定"C1" 作为第二种颜色。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Wanted palette details
enmax_palette = ["#808282", "#C2CD23", "#918BC3"]

sns.set_palette(palette=enmax_palette)

x=np.random.randn(100)
g = sns.distplot(x, color="C1")

plt.show()

操作 matplotlib 颜色字典。

所有命名颜色都存储在字典中,您可以通过以下方式访问

matplotlib.colors.get_named_colors_mapping()

您可以使用自定义名称和颜色来更新此词典。请注意,这将覆盖现有的同名颜色。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import seaborn as sns

# Wanted palette details
enmax_palette = ["#808282", "#C2CD23", "#918BC3"]
color_codes_wanted = ['grey', 'green', 'purple']
cdict = dict(zip(color_codes_wanted, [mcolors.to_rgba(c) for c in enmax_palette]))

mcolors.get_named_colors_mapping().update(cdict)
x=np.random.randn(100)
g = sns.distplot(x, color="green")

plt.show()

此处显示的所有代码都将以“公司的绿色”颜色生成相同的图:

【讨论】:

  • 请注意,对于许多大面积的绘图,saturation 参数(默认为 0.75)会影响所使用的实际颜色。对于在调色板中使用精确十六进制值的人来说,这可能会非常令人困惑。
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 2011-10-25
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 2011-01-28
相关资源
最近更新 更多