gpt4 book ai didi

python - matplotlib bwr-colormap,始终以零为中心

转载 作者:太空狗 更新时间:2023-10-29 21:07:12 28 4
gpt4 key购买 nike

我正在尝试绘制一个包含正数和负数的矩阵。数字将在 -1 到 1 的区间内,但不在完整范围内。例如,数字有时可能在 -0.2 到 +0.8 的范围内(参见下面的代码)。我想使用 bwr-colormap(蓝色 -> 白色 - 红色),这样零总是用白色进行颜色编码。 -1 应该用尽可能深的蓝色进行颜色编码,+1 应该用尽可能深的红色进行颜色编码。下面是一个示例,其中两个图只能通过颜色条来区分。

import numpy
from matplotlib import pyplot as plt

# some arbitrary data to plot
x = numpy.linspace(0, 2*numpy.pi, 30)
y = numpy.linspace(0, 2*numpy.pi, 20)
[X, Y] = numpy.meshgrid(x, y)
Z = numpy.sin(X)*numpy.cos(Y)

fig = plt.figure()
plt.ion()
plt.set_cmap('bwr') # a good start: blue to white to red colormap

# a plot ranging from -1 to 1, hence the value 0 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 1)
plt.pcolor(X, Y, Z)
plt.colorbar()

# a plot ranging from -0.2 to 0.8 hence 0.3 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 2)
plt.pcolor(X, Y, Z*0.5 + 0.3) # rescaled Z-Data
plt.colorbar()

此代码创建的图形可以在这里看到:figure create with posted code

如上所述,我正在寻找一种始终使用相同颜色对值进行颜色编码的方法,其中 -1:深蓝色,0:白色,+1:深红色。这是单行本,我遗漏了什么,还是我必须为此自己写一些东西?

编辑:在深入挖掘之后,我自己找到了一个令人满意的答案,没有触及颜色图,而是使用 pcolor 的可选输入(见下文)。不过,我不会删除这个问题,因为在我发布这个问题并点击相关问题/答案之前,我找不到关于 SO 的答案。另一方面,我不介意它是否被删除,因为如果您正在寻找合适的关键字,可以在其他地方找到这个问题的确切答案。

最佳答案

您可以像这样使用 matplotlib.colors.TwoSlopeNorm:

# define your scale, with white at zero
vmin = -0.2
vmax = 0.8
norm = colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)

在你的例子中,

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

# some arbitrary data to plot
x = numpy.linspace(0, 2*numpy.pi, 30)
y = numpy.linspace(0, 2*numpy.pi, 20)
[X, Y] = numpy.meshgrid(x, y)
Z = numpy.sin(X)*numpy.cos(Y)

fig = plt.figure()
plt.ion()
plt.set_cmap('bwr') # a good start: blue to white to red colormap

# a plot ranging from -1 to 1, hence the value 0 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 1)
plt.pcolor(X, Y, Z)
plt.colorbar()

# a plot ranging from -0.2 to 0.8 hence 0.3 (the average) is colorcoded in white
ax = fig.add_subplot(1, 2, 2)

# define your scale, with white at zero
vmin = -0.2
vmax = 0.8
norm = colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)

plt.pcolor(X, Y, Z, vmin=vmin, vmax=vmax, norm=norm)
plt.colorbar()

会给你:

enter image description here

关于python - matplotlib bwr-colormap,始终以零为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500541/

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