gpt4 book ai didi

python - 如何从颜色条图像中提取颜色图并将其用于热图中

转载 作者:行者123 更新时间:2023-12-05 03:29:02 24 4
gpt4 key购买 nike

我需要根据阈值生成色标,如下所示:

Required Color Scale

目前,我只能填充色标,如下所示:

def create_png(a_group,req_df):
import matplotlib.pyplot as plt
plt.figure(figsize=(15, 8))
heat_plot = sns.heatmap(req_df, vmin=-120, vmax=-80, cmap="viridis", yticklabels=False,square=True,linecolor='black',linewidths=.5)
fig = heat_plot.get_figure()

Color scale generated from the above script

最佳答案

您可以从颜色列表创建一个ListedColormap。以下方法从颜色图中读取图像并提取彩色矩形中心的 45 种颜色。请注意,如果原始图像不通过 jpeg 保存为 ax png,质量会好一些。由于 jpeg 稍微混合了颜色,因此它们可能与原始文件略有不同。

import matplotlib.pyplot as plt
import numpy as np

img = plt.imread('desired_colormap.jpg')
# x and y positions of the rectangle centers are found via an image editor
xpos = 12
ypos_124 = 768
ypos_80 = 22
val_min = -124
val_max = -80
# extract the color from each of 45 rectangles
colors = [img[int(ypos), xpos] / 255
for ypos in np.linspace(ypos_124, ypos_80, val_max - val_min + 1)]

然后您可以使用此颜色列表创建颜色图并在 seaborn 中使用它。看起来有点迷幻。

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import numpy as np
from scipy.ndimage import gaussian_filter

# colors were read from image

# create some smooth test data, with the given range of values
data = gaussian_filter(np.random.rand(1000, 1000), 20)
data -= data.min()
data *= (val_max - val_min) / data.max()
data += val_min

fig, ax = plt.subplots(figsize=(12, 10))
sns.set_style('white')
sns.heatmap(data=data, xticklabels=[], yticklabels=[],
cmap=ListedColormap(colors), vmin=val_min - 0.5, vmax=val_max + 0.5,
cbar_kws={'ticks': np.arange(val_min, val_max + 1)}, ax=ax)
plt.tight_layout()
plt.show()

sns.heatmap using custom colormap

PS:如果你想保存列表供多次使用,你可以将颜色转换为十六进制(matplotlib.color.to_hex)。该列表将是

colors = ['#000000', '#000000', '#68696b', '#00008c', '#0001cd', '#0102fa', '#4467e5', '#6296ea', '#4683b2',
'#4981b4', '#007f85', '#2d8a5d', '#619ca2', '#65cdaa', '#0afafb', '#02f99e', '#74fc02', '#adff31',
'#f6fbd2', '#f0e7ac', '#f1e68a', '#fbff0a', '#fdda00', '#dba51e', '#f9a608', '#ff8a06', '#d16920',
'#8d4312', '#fe804e', '#fe5945', '#fd4900', '#fe0300', '#fcb2c1', '#f0807c', '#fd6ba9', '#fc02f9',
'#dd9ee4', '#ba55d7', '#9202d6', '#85038b', '#7f017c', '#480181', '#4c0084', '#4b007f', '#480185']

关于python - 如何从颜色条图像中提取颜色图并将其用于热图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71090534/

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