python - 使用十六进制代码设置自定义 seaborn 调色板,并命名颜色

标签 python matplotlib seaborn

我的公司有一个正式的调色板,所以我需要在我的 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”列表为颜色分配简单的名称。

最佳答案

使用自定义函数

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

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

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

enter image description here

关于python - 使用十六进制代码设置自定义 seaborn 调色板,并命名颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52652264/

相关文章:

python - python中变量是如何创建和销毁的?

python - 从图像中的绝对点创建相对点网格

python - 交替合并两个列表的n个元素

python - matplotlib 中的偏移辅助轴

python - Seaborn:如何在 catplot 中设置自定义 "hue"标签而不是自动标签

python - 绘制包含数百万行的列

python - wxPython或wxPython中的PyGame Canvas ->哪个更快?

python - 在一张图中绘制多个 Pandas 数据框

python - 如何将每年绘制为一条线,x 轴为月份

python - 缩放时保持绘图内的线标签可见