如何更改颜色栏的颜色(以某个特定的值间隔)? [英] How to change colorbar's color (in some particular value interval)?

查看:59
本文介绍了如何更改颜色栏的颜色(以某个特定的值间隔)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matplotlib中,我想以某个特定的值间隔更改颜色栏的颜色.例如,我想更改地震色条,让-0.5到0.5之间的值变成白色,我该怎么做?

In matplotlib, I would like to change colorbar's color in some particular value interval. For example, I would like to change the seismic colorbar, to let the values between -0.5 and 0.5 turn white, how can I do this?

非常感谢

推荐答案

基本上,您需要创建自己的具有所需特定功能的色图.当然,这样做时可以使用现有的颜色图.

You basically need to create your own colormap that has the particular features you want. Of course it is possible to make use of existing colormaps when doing so.

颜色图的范围总是在 0 1 之间.然后,该范围将映射到数据间隔.因此,为了在 -0.5 0.5 之间创建白色,我们需要知道数据范围-假设数据从 -1 到<代码> 1 .然后,我们可以决定使地震图的下部(蓝色)从 -1 变为 -0.5 ,然后在 -0.5 和 +0.5 ,最后是地震图的上部(红色),从 0.5 1 .在颜色图的语言中,这对应于范围 [0,0.25] [0.25,0.75] [0.75,1] .然后,我们可以创建一个列表,其中前25%和后25%是地震图的颜色,中间50%是白色.

Colormaps are always ranged between 0 and 1. This range will then be mapped to the data interval. So in order to create whites between -0.5 and 0.5 we need to know the range of data - let's say data goes from -1 to 1. We can then decide to have the lower (blues) part of the seismic map go from -1 to -0.5, then have white between -0.5 and +0.5 and finally the upper part of the seismic map (reds) from 0.5 to 1. In the language of a colormap this corresponds to the ranges [0,0.25], [0.25, 0.75] and [0.75,1]. We can then create a list, with the first and last 25% percent being the colors of the seismic map and the middle 50% white.

此列表可用于使用 matplotlib.colors.LinearSegmentedColormap.from_list("colormapname",listofcolors)创建颜色表.

This list can be used to create a colormap, using matplotlib.colors.LinearSegmentedColormap.from_list("colormapname", listofcolors).

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

n=50
x = 0.5
lower = plt.cm.seismic(np.linspace(0, x, n))
white = plt.cm.seismic(np.ones(100)*0.5)
upper = plt.cm.seismic(np.linspace(1-x, 1, n))
colors = np.vstack((lower, white, upper))
tmap = matplotlib.colors.LinearSegmentedColormap.from_list('terrain_map_white', colors)

x = np.linspace(0,10)
X,Y = np.meshgrid(x,x)
z = np.sin(X) * np.cos(Y*0.4)

fig, ax = plt.subplots()
im = ax.imshow(z, cmap=tmap)    
plt.colorbar(im)

plt.show() 

对于更一般的情况,您可能需要进行颜色标准化(使用 matplotlib.colors.Normalize ).参见例如此示例,其中颜色图中的某些颜色始终是固定为0,与数据范围无关.

For more general cases, you may need a color normalization (using matplotlib.colors.Normalize). See e.g. this example, where a certain color in the colormap is always fixed at a data value of 0, independent of the data range.

这篇关于如何更改颜色栏的颜色(以某个特定的值间隔)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆