【问题标题】:Keep the linear colors of a colormap while using non-linear levels in plt.contourf在 plt.contourf 中使用非线性级别时保持颜色图的线性颜色
【发布时间】:2018-02-02 07:29:54
【问题描述】:

在以下示例中,我想手动将contourf 绘图的levels 设置为某个变量的分位数(以增强可视化)。

但是给出levels 也会影响colormap 的颜色缩放(看看红色是如何扩展的-> 视觉印象不受影响):我怎样才能让它们保持线性?

换句话说,如何保持颜色条的颜色与顶部子图中一样,但与底部子图中的值相对应?

import matplotlib.pyplot as plt
import numpy as np

xvec = np.linspace(-10.,10.,100)
x,y = np.meshgrid(xvec, xvec)
z = -(x**2 + y**2)**2

fig, (ax0, ax1) = plt.subplots(2)
p0 = ax0.contourf(x, y, z, 100)
fig.colorbar(p0, ax=ax0)
p1 = ax1.contourf(x, y, z, 100, levels=np.percentile(z, np.linspace(0,100,101)))
fig.colorbar(p1, ax=ax1)

plt.show()

我是否错过了一些简单的解决方案(我打赌是的),还是我应该尝试做一些matplotlib.colors.LinearSegmentedColormap 操作...?!

【问题讨论】:

    标签: python matplotlib colormap color-mapping


    【解决方案1】:

    您可以使用matplotlib.colors.BoundaryNorm 指定用于颜色映射的级别。

    import matplotlib.pyplot as plt
    import matplotlib.colors 
    import numpy as np
    
    xvec = np.linspace(-10.,10.,100)
    x,y = np.meshgrid(xvec, xvec)
    z = -(x**2 + y**2)**2
    
    fig, (ax0, ax1) = plt.subplots(2)
    p0 = ax0.contourf(x, y, z, 100)
    fig.colorbar(p0, ax=ax0)
    
    levels = np.percentile(z, np.linspace(0,100,101))
    norm = matplotlib.colors.BoundaryNorm(levels,256)
    p1 = ax1.contourf(x, y, z, 100, levels=levels, norm=norm)
    fig.colorbar(p1, ax=ax1)
    
    plt.show()
    

    【讨论】:

    • 完美,谢谢!我想 256 是任何原始colormap 中的级别数。效果很好,谢谢。我想知道......一个人是如何意识到这种精致的选择的?我阅读了有关颜色图规范化 (matplotlib.org/users/colormapnorms.html) 等的文档,但从未遇到过此 matplotlib.colors.BoundaryNorm... 我们在哪里学习这些东西?
    • 是的 256 是颜色图中的颜色数。如果你有一个颜色图cmap,你会得到这个数字cmap.N。在您链接到的那篇文章中,有一个部分 Discrete bounds 告诉我们有关 BoundaryNorm 的信息。
    猜你喜欢
    • 2016-02-25
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2019-08-15
    • 2018-06-22
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多