如何制作附加此颜色条图像的颜色图?

How to make colormap of this colorbar image attached?

0

我想制作一张用于附件图像的色图。

 img = imread('/path/Screenshot 2022-04-12 at 2.14.16 PM.png')
 colors_from_img = img[:, 0, :]
 my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img, N=651)
 y = random_sample((100, 100))
 imshow(y, cmap=my_cmap);plt.colorbar().png')

期待您的意见

您只需将我评论中链接的策略从垂直方向转换为水平方向即可。为了避免随机猜测,您首先分析图像尺寸,然后猜测水平线应该是什么水平(大约 66/3)以及颜色条的步长是多少(大约 616/11)。最后,您必须 normalize the image 范围 -0.3 ... 0.5 并告诉 matplotlib 还应考虑高于和低于的值 (extend="both")。这导致我们:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, BoundaryNorm
import numpy as np

img = plt.imread('test.png')
#analyze image dimensions
#print(img.shape)
#>>> (66, 616, 4)
colors_from_img = img[22, 60::56, :]

#generate color map
my_cmap = LinearSegmentedColormap.from_list("my_cmap", colors_from_img, N=len(colors_from_img))
#normalize with boundaries
my_norm = BoundaryNorm(np.linspace(-0.3, 0.5, 9), my_cmap.N, extend="both")
y = 2*np.random.random_sample((20, 20))-1
plt.imshow(y, cmap=my_cmap, norm=my_norm)
plt.colorbar()
plt.show()

示例输出:

如果您只希望颜色条是图像,我建议教程中的公式为 example。我已经将颜色名称设置为与您图片中的颜色相似,但您可以将它们更改为您喜欢的任何颜色。

import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots(figsize=(6, 0.5))
fig.subplots_adjust(bottom=0.5)
c = ['darkblue', 'lightblue', 'aquamarine', 'green', 'lime', 'yellow','orange','red']
cmap = (mpl.colors.ListedColormap(c)
        .with_extremes(over='purple', under='white'))

bounds = [-0.3,-0.2,-0.1,0,0.1,0.2,0.3,0.4,0.5]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
fig.colorbar(
    mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    cax=ax,
    boundaries=[-10] + bounds + [10],
    extend='both',
    extendfrac='auto',
    ticks=bounds,
    spacing='uniform',
    orientation='horizontal',
    #label='Custom extension lengths, some other units',
)
fig.savefig('my_colorbar.png')
plt.show()