gpt4 book ai didi

python - 在 Matplotlib 中设置与特定数据范围相对应的离散颜色图

转载 作者:行者123 更新时间:2023-12-01 03:33:30 25 4
gpt4 key购买 nike

一些背景

我有一个形状为(50,50)的二维数组,数据值的范围是-40 ~ 40。
但我想将数据绘制在三个数据范围[<0], [0,20], [>20]

然后,我需要生成与这三个部分相对应的颜色图。

我现在有一些想法

## ratio is the original 2-d array
binlabel = np.zeros_like(ratio)
binlabel[ratio<0] = 1
binlabel[(ratio>0)&(ratio<20)] = 2
binlabel[ratio>20] = 3

def discrete_cmap(N, base_cmap=None):
base = plt.cm.get_cmap(base_cmap)
color_list = base(np.linspace(0, 1, N))
cmap_name = base.name + str(N)
return base.from_list(cmap_name, color_list, N)

fig = plt.figure()
ax = plt.gca()
plt.pcolormesh(binlabel, cmap = discrete_cmap(3, 'jet'))
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="4%", pad=0.45)
cbar = plt.colorbar(ratio_plot, cax=cax, orientation="horizontal")
labels = [1.35,2,2.65]
loc = labels
cbar.set_ticks(loc)
cbar.ax.set_xticklabels(['< 0', '0~20', '>20'])

有没有更好的方法?任何建议将不胜感激。

最佳答案

使用 ListedColormap 对其他问题有多种答案和 BoundaryNorm ,但这里有一个替代方案。我忽略了您的颜色条的位置,因为这与您的问题无关。

您可以替换您的binlabel调用 np.digitize() 进行计算并替换您的 discrete_cmap()使用lut功能get_cmap() 的参数。另外,我发现将颜色边界放置在索引之间 0.5 的中点处比缩放到尴尬的奇数分数更容易:

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

ratio = np.random.random((50,50)) * 50.0 - 20.0

fig2, ax2 = plt.subplots(figsize=(5,5))

# Turn the data into an array of N bin indexes (i.e., 0, 1 and 2).
bounds = [0,20]
iratio = np.digitize(ratio.flat,bounds).reshape(ratio.shape)

# Create a colormap containing N colors and a Normalizer that defines where
# the boundaries of the colors should be relative to the indexes (i.e., -0.5,
# 0.5, 1.5, 2.5).
cmap = cm.get_cmap("jet",lut=len(bounds)+1)
cmap_bounds = np.arange(len(bounds)+2) - 0.5
norm = mcol.BoundaryNorm(cmap_bounds,cmap.N)

# Plot using the colormap and the Normalizer.
ratio_plot = plt.pcolormesh(iratio,cmap=cmap,norm=norm)
cbar = plt.colorbar(ratio_plot,ticks=[0,1,2],orientation="horizontal")
cbar.set_ticklabels(["< 0","0~20",">20"])

Example discrete color bar

关于python - 在 Matplotlib 中设置与特定数据范围相对应的离散颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601997/

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