【问题标题】:Center diverging colors to zero中心发散颜色为零
【发布时间】:2020-09-26 05:33:39
【问题描述】:

我想绘制以 0 为中心的不同颜色(红色表示正值,蓝色表示负值)。 我尝试按照建议 here

将数据标准化为 0 作为中点
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()

我明白了

它并没有真正遵循 -4 到 1.5 的范围,我如何也增加间隔,特别是突出更多的正值。

【问题讨论】:

  • 颜色条在这张图片中是错误的,那是因为你在 1.5 时没有轮廓。尝试使用轮廓 kwarg 显式设置轮廓级别。

标签: python python-3.x matplotlib colorbar


【解决方案1】:

下面的绘图是使用matplotlib.colors.DivergingNorm 完成的,并将levels 的列表显式传递给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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多