我想从 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()
但是,如果您在颜色列表中还没有渐变(如上所述),那么使用 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 betweenx[i]
andx[i+1]
, the output value of a given color will be linearly interpolated betweeny1[i]
andy0[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()
假设输入列表colors
具有正确的RGB格式。
关于python - 如何在seaborn中从RGB颜色列表构建颜色图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671673/