python - 如何在seaborn中从RGB颜色列表构建颜色图?

标签 python colors seaborn

我想从 RGB 颜色列表开始,并从中构建一个可以在 seaborn 图中使用的颜色图。我找到了一些有关如何更改默认颜色图的说明,但这不是我想要的。我想构建一个颜色图,可以在 kdeplot 命令的 cmap 参数中使用。

最佳答案

构建 matplotlib.colors.ListedColormap从颜色列表中选择是相当微不足道的。以下是使用 tableau 20 调色板中前 4 种颜色的示例 -

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib import cm

# Tableau 20 color palette for demonstration
colors = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120)]
# Conversion to [0.0 - 1.0] from [0.0 - 255.0]
colors = [(e[0] / 255.0, e[1] / 255.0, e[2] / 255.0) for e in colors]

cmap = ListedColormap(colors)

a = np.outer(np.linspace(0, 1, 20), np.linspace(0, 1, 20))
im = plt.imshow(a, cmap=cmap)
plt.colorbar(im)
plt.show()

enter image description here

但是,如果您在颜色列表中还没有渐变(如上所述),那么使用 matplotlib.colors.LinearSegmentedColormap 可能会更有用。反而。由于预期的格式,这有点棘手,

[...] segmentdata argument is a dictionary with a set of red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table [...].
Each row in the table for a given color is a sequence of x, y0, y1 tuples. In each sequence, x must increase monotonically from 0 to 1. For any input value z falling between x[i] and x[i+1], the output value of a given color will be linearly interpolated between y1[i] and y0[i+1]

这样的字典可以通过下面例子中的方法通过算法生成

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import cm

# Tableau 20 color palette for demonstration
colors = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120)]
colors = [(e[0] / 255.0, e[1] / 255.0, e[2] / 255.0) for e in colors]

nc = len(colors)
c = np.zeros((3, nc, 3))
rgb = ['red', 'green', 'blue']
for idx, e in enumerate(colors):
    for ii in range(3):
        c[ii, idx, :] = [float(idx) / float(nc - 1), e[ii], e[ii]]

cdict = dict(zip(rgb, c))
cmap = LinearSegmentedColormap('tab20', cdict)

a = np.outer(np.linspace(0, 1, 20), np.linspace(0, 1, 20))
im = plt.imshow(a, cmap=cmap)
plt.colorbar(im)
plt.show()

enter image description here

假设输入列表colors具有正确的RGB格式。

关于python - 如何在seaborn中从RGB颜色列表构建颜色图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671673/

相关文章:

python - 了解将密集层连接到 LSTM

python - 如何使用 py-amqplib 在多个队列上等待消息

python - 如何在 CherryPy 中设置 CORS

r - scale_color_manual 颜色不会改变

r - 从热图或基础数据中提取颜色值矩阵

python - Seaborn 的箱线图 mustache 的含义

python - 使用补丁自定义散点图中的图例标记面部颜色

python - 在 FBX SDK 中创建点或顶点

javascript - 你如何通过用户输入javascript html设置对象的颜色

python - 如何将 seaborn boxplot 须基于百分位数?