python - 将发散颜色居中至零

标签 python python-3.x matplotlib colorbar

我想用以 0 为中心的不同颜色进行绘图(红色表示正值,蓝色表示负值)。 我尝试按照建议以 0 作为中点对数据进行标准化 here

import matplotlib.colors as colors
import numpy as np

class MidpointNormalize(colors.Normalize):
    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        colors.Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))

minzz = -4
maxzz = 1.5 

plt.contourf(x, y, z, cmap='RdBu_r',  norm=MidpointNormalize(midpoint=0), vmin=minzz, vmax=maxzz)
plt.xticks()
plt.colorbar()

我明白了

enter image description here

它并不真正遵循 -4 到 1.5 的范围,我如何增加间隔,特别是为了突出显示更多的正值。

最佳答案

更新

matplotlib.colors.DivergingNorm 从 Matplotlib 3.2 开始已被删除,请使用 matplotlib.colors.TwoslopeNorm,其用法与删除的范数相同。


以下绘图是使用 matplotlib.colors.DivergingNorm 完成的并显式地将级别列表传递给plt.contourf,因为否则轮廓算法会为负值和正值选择相同长度的间隔(这不是一个通常想要)。

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

t = np.linspace(-3.1, 3.1, 63)
x, y = np.meshgrid(t, t)
r = np.sqrt(x**2+y**2)
z = -2*np.cos(2*r)-1 # max = 1, min = -3

fig, ax = plt.subplots()
ax.set_aspect(1)
img = ax.contourf(x, y, z, levels=[-3,-2.5,-2,-1.5,-1,-0.5,0,0.25,0.5, 0.75, 1],
                  cmap='RdBu_r',
                  norm=DivergingNorm(0))
plt.colorbar(img)
plt.show()

center

关于python - 将发散颜色居中至零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241963/

相关文章:

python - Jupyter Notebook 中的交互式 Bokeh 图未更新

python - crontab 不会运行 os.system python 命令

python - Python 2.6 和 3 中的字节与字节数组

python - matplotlib:在刻度标签中使用固定的小数位数和科学记数法

python - 使用 BeautifulSoup 从 Github 页面提取文件名列表

python-3.x - 与 pytest 一起使用时禁用日志记录

python - 用频率表绘制频率分布/直方图

python - 获取 Pandas 数据框中的最大连续空行

使用自定义双括号格式的 Python 模板安全替换

python - numpy 数组 : replace nan values with average of columns