色彩均匀分布的颜色条的数据不均匀(不规则)

时间:2020-05-19 17:40:57

标签: python matplotlib colorbar

我正在尝试创建一个具有13个色阶的色条,并使用中心值间隔为0的发散的RdBu_r色图。目前,我有an evenly spaced colorbar with values descending by 8 ranging from -48 to +48

我要制作的是一个色条,该色条具有均匀的彩色间距,但间距不均匀,like this colorbar which I modified in photoshop, such that the values go from [-96.0, -72, -48, -24, -12, -6, 0, 6, 12, 24, 48, 72, 96]

我当前的尝试如下:

from cartopy import crs as ccrs;  import matplotlib.pyplot as plt

crs_new = ccrs.PlateCarree()

fig, axs = plt.subplots(subplot_kw={'projection': crs_new},figsize=(8, 6))

cmap = 'RdBu_r'  

uneven_levels = [-96.0, -72, -48, -24, -12, -6, 0, 6, 12, 24, 48, 72, 96]
vmin,vmax = -48,48
cs=plt.pcolormesh(lon,lat, data,cmap=cmap, transform=crs_new,vmin=vmin,vmax=vmax)
cbar=plt.colorbar(cs,boundaries= uneven_levels)

Which results in a colorbar with really dark ends and clearly uses linearly spaced coloring.

使用countourf和“ spacing =制服”无效。

使用“ colors.DivergingNorm(vmin = vmin,vcenter = 0,vmax = vmax)”无效。

我尝试使用

定义自己的颜色条
cmap = plt.get_cmap('RdBu_r')
colors = cmap(np.linspace(0, 1, len(uneven_levels)))

但不知道要使数据与这些级别相匹配,结果与图3相同,因此这也不起作用。

任何帮助将不胜感激! :)

1 个答案:

答案 0 :(得分:0)

存在很多深色的原因是vmin, vmax = -48, 48-48以下的所有值强制为最深的蓝色,并将48以上的所有值强制为最暗的红色。

要获得与contourf类似的效果,matplotlib的from_levels_and_colors可能会有所帮助。这将生成具有12种颜色和一个范数的颜色图。规范是一项功能,可将-96到96之间的值转换为颜色映射的值(由级别定义)。

这是一些示例代码:

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.colors as mcolors

x = np.linspace(0, 3 * np.pi, 500)
data = np.sin(x - x[:, np.newaxis] * 2) * 95
uneven_levels = [-96, -72, -48, -24, -12, -6, 0, 6, 12, 24, 48, 72, 96]
cmap_rb = plt.get_cmap('RdBu_r')
colors = cmap_rb(np.linspace(0, 1, len(uneven_levels) - 1))
cmap, norm = mcolors.from_levels_and_colors(uneven_levels, colors)

fig, axs = plt.subplots(ncols=2, figsize=(8, 6))

v = np.linspace(-96, 96, 1000)
axs[0].plot(v, norm(v))

cs = axs[1].pcolormesh(data, cmap=cmap, norm=norm)
cbar = fig.colorbar(cs, ticks=uneven_levels)

plt.show()

左图显示了边界范数如何以非线性方式将-96和96之间的值映射到其各自的颜色。右图显示带有边界的颜色栏。

example plot