从调色板种均匀取出一些颜色,颜色不会重复,颜色数量可以随机
参考:https://stackoverflow.com/questions/55469432/is-there-a-similar-color-palette-to-tab20c-with-bigger-number-of-colors
颜色参考:https://matplotlib.org/stable/tutorials/colors/colormaps.html
def random_colormap(N: int,cmaps_='gist_ncar',show_=False):
# 从颜色图(梯度多)中取N个
# test_cmaps = ['gist_rainbow', 'nipy_spectral', 'gist_ncar']
cmap = matplotlib.colors.ListedColormap(plt.get_cmap(cmaps_)(np.linspace(0, 1, N)))
if show_:
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
fig, ax = plt.subplots(1, 1, figsize=(5, 1))
ax.imshow(gradient, aspect='auto', cmap=cmap)
plt.show()
return cmap
从不同的颜色图中取颜色并合并,每个base中颜色梯度为20,也就是最多取60个颜色
base_cmaps = [‘tab20’,‘tab20b’,‘tab20c’]可以添加其他palette,但是要注意颜色梯度数量
def random_colormap2(N: int,base_cmaps=['gist_ncar'],show_=False):
# 从不同的颜色图中取颜色并合并,每个base中颜色梯度为20,也就是最多60个颜色
base_cmaps = ['tab20','tab20b','tab20c']
N //= len(base_cmaps)
# N += 1
# base_cmaps = ['Greys', 'Purples', 'Reds', 'Blues', 'Oranges', 'Greens']
# segmented_cmaps = [matplotlib.colors.ListedColormap(plt.get_cmap(t)(np.linspace(0,1,N))) for t in test_cmaps]
colors = np.concatenate([plt.get_cmap(name)(np.linspace(0, 1, N)) for name in base_cmaps])
cmap = matplotlib.colors.ListedColormap(colors)
if show_:
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
fig, ax = plt.subplots(1,1,figsize=(5,1))
ax.imshow(gradient, aspect='auto', cmap=cmap)
plt.show()
return cmap
random_colormap(40, cmaps_='gist_ncar', show_=True)
cmaps = random_colormap2(60, base_cmaps=['gist_ncar'], show_=True)
如果颜色太多,推荐使用第一种,毕竟颜色梯度变化是连续的