【问题标题】:Create a LinearSegmentedColormap with values within range使用范围内的值创建一个 LinearSegmentedColormap
【发布时间】:2021-03-06 22:42:49
【问题描述】:

我想在matplotlib gridspec 图像中绘制几个网格。每个图像都有一个颜色图,我想让该颜色图对所有图像都可解释。 为此,我需要创建一个将应用于所有图像的通用颜色图。取值范围应介于所有图像值的最小值和所有图像值的最大值之间。

因此,我需要创建一个LinearSegmentedColormap,我可以在其中定义最大值和最小值。

是否可以定义表示颜色图谱的值?

例子:

1 - 三个值是(从左到右):-2.024131、-3.837179、-2.947026

2 - -2.343214, -4.110780, -1.029205

1 的第一个颜色是白色,而 2 的颜色是红色,尽管值非常接近。发生的情况是颜色是在每个图像的三个值内计算的,因此无法比较两个图像 - 比例不同。

我想要的是创建一个通用颜色图,然后从全局范围中检索每个图像的值。

亲切的问候

【问题讨论】:

  • 你不能为 0-1-2 创建一个 LinearSegmentedColormap green-red-white,然后将每个三元组按升序转换为 0-1-2 值吗? vmin-vmax 不能保证你的中间值会在红色范围内。

标签: matplotlib colormap


【解决方案1】:

如果您真的需要一个通用颜色图,您可以创建一个BoundaryNorm,其边界正好位于颜色值的中间:

from matplotlib import pyplot as plt
import matplotlib as mpl

def min_val(combinations, color):
    return min([x for xs, cs in combinations for x, c in zip(xs, cs) if c == color])

def max_val(combinations, color):
    return max([x for xs, cs in combinations for x, c in zip(xs, cs) if c == color])

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)

colors = ['grey', 'red', 'white']  # ordered from lowest to highest
combinations = [[[-2.024131, -3.837179, -2.947026], ['white', 'grey', 'red']],
                [[-2.343214, -4.110780, -1.029205], ['red', 'grey', 'white']]]
bounds = [min_val(combinations, 'grey'),
          (max_val(combinations, 'grey') + min_val(combinations, 'red')) / 2,
          (max_val(combinations, 'red') + min_val(combinations, 'white')) / 2,
          max_val(combinations, 'white')]

cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.BoundaryNorm(bounds, len(colors))
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
                                 norm=norm,
                                 orientation='horizontal')
cbar.set_label("Boundary norm")
fig.show()

另一种方法结合了LinearSegmentedColormapTwoSlopeNorm

colors = ['grey', 'red', 'white']  # ordered from lowest to highest
combinations = [[[-2.024131, -3.837179, -2.947026], ['white', 'grey', 'red']],
                [[-2.343214, -4.110780, -1.029205], ['red', 'grey', 'white']]]
bounds = [(min_val(combinations, c) + max_val(combinations, c)) / 2 for c in colors]

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.colors.LinearSegmentedColormap.from_list('segmented', colors)
norm = mpl.colors.TwoSlopeNorm(vcenter=bounds[1], vmin=bounds[0], vmax=bounds[2])
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
                                 norm=norm,
                                 orientation='horizontal')
cbar.set_label("TwoSlopeNorm")
fig.show()

【讨论】:

  • 我考虑过这一点,但通过这种方法,我会将我的值范围缩小到 x 颜色,从而丢失信息。想法是保留 cmap 的颜色光谱并使其对所有图像通用
  • 这个 TwoSlopeNorm 是否更接近您的要求?如果没有,您能否编辑您的问题并添加更多详细信息?
猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多