gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:10:21 27 4
gpt4 key购买 nike

我想从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com