如何解决创建一个值在范围内的 LinearSegmentedColormap
我想在 matplotlib
gridspec 图像中绘制多个网格。每个图像都有一个颜色图,我想让该颜色图对所有图像都可解释。
为此,我需要创建一个将应用于所有图像的通用颜色图。值范围应介于所有图像值的最小值和所有图像值的最大值之间。
因此,我需要创建一个 LinearSegmentedColormap
来定义最大值和最小值。
是否可以定义表示颜色图谱的值?
示例:
1 - 三个值(从左到右): -2.024131,-3.837179,-2.947026
2 - -2.343214,-4.110780,-1.029205
1 的第一个颜色是白色,而 2 的第一个颜色是红色,尽管值非常接近。发生的情况是颜色是在每个图像的三个值内计算的,因此无法比较两个图像 - 比例不同。
我想要的是创建一个通用颜色图,然后从全局范围中检索每个图像的值。
亲切的问候
解决方法
如果你真的需要一个通用的颜色图,你可以创建一个 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) 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','white']]]
bounds = [min_val(combinations,'grey'),(max_val(combinations,'grey') + min_val(combinations,'red')) / 2,'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()
另一种方法结合了 LinearSegmentedColormap
和 TwoSlopeNorm
:
colors = ['grey','white']]]
bounds = [(min_val(combinations,c) + max_val(combinations,c)) / 2 for c in colors]
fig,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,orientation='horizontal')
cbar.set_label("TwoSlopeNorm")
fig.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。