Nra*_*ras 8 python colors matplotlib
我试图用正数和负数绘制矩阵.数字将在-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()
Run Code Online (Sandbox Code Playgroud)
此代码创建的图形可以在这里看到:
如上所述,我正在寻找一种方法来始终使用相同的颜色对值进行颜色编码,其中-1:深蓝色,0:白色,+ 1:深红色.这是一个单行,我错过了什么或者我是否必须为此自己写点什么?
编辑:经过一段时间的挖掘后,我自己找到了一个令人满意的答案,没有触及色彩图,而是使用可选输入pcolor(见下文).不过,我不会删除这个问题,因为在我发布这个问题并点击相关的问题/答案之前我找不到答案.另一方面,我不介意它是否被删除,因为如果一个人正在寻找合适的关键字,可以在其他地方找到这个问题的答案.
您可以像这样使用 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)
Run Code Online (Sandbox Code Playgroud)
在你的例子中,
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)
# 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()
Run Code Online (Sandbox Code Playgroud)
会给你:
显然,我在挖掘了更长的时间后自己找到了答案。pcolor提供可选的输入vmin和vmax. 如果我将它们分别设置为-1和1,就完全解决了问题。颜色编码似乎与 vmin 和 vmax 相关,而不是与绘制的数据的最小值和最大值相关。因此将绘图命令(和注释)更改为
# a plot ranging from -1 to 1, where the value 0 is colorcoded in white
ax = fig.add_subplot(1, 2, 1)
plt.pcolor(X, Y, Z, vmin=-1, vmax=1) # vmin, vmax not needed here
plt.colorbar()
# a plot ranging from -0.2 to 0.8, where the value 0 is colorcoded in white
ax = fig.add_subplot(1, 2, 2)
plt.pcolor(X, Y, Z*0.5 + 0.3, vmin=-1, vmax=1) # rescaled Z-Data
plt.colorbar()
Run Code Online (Sandbox Code Playgroud)
它根据我的需要生成一个图形:
因此,设置vmin=-1, vmax=1就可以完成工作,我不必更改颜色图本身的内容。
| 归档时间: |
|
| 查看次数: |
8189 次 |
| 最近记录: |