简体   繁体   English

Python matplotlib使用colormap更改contourf plot中指定值的颜色

[英]Python matplotlib change color of specified value in contourf plot using colormap

I am trying to create a filled contour plot in matplotlib using colormap. 我正在尝试使用colormap在matplotlib中创建一个填充的等高线图。 I want to change color of the specified value. 我想改变指定值的颜色。

For example, 例如,

levs = [-3,-1,1,3]
plt.contourf(x,y,z,levs,cmap=cm.jet,extend='both')

I hope the color between -1 and 1 to white keeping the other colors default colormap. 我希望-1和1之间的颜色为白色,保持其他颜色默认的colormap。

Sorry for my bad english. 对不起,我的英语不好。 Any help would be appreciated. 任何帮助,将不胜感激。

I would just overplot the same contour plot, but then just with levels between -1 and 1, with color white. 我只是绘制相同的轮廓图,但只是在-1和1之间的水平,颜色为白色。

For example: 例如:

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np

x, y = np.mgrid[-100:100,-100:100]
x /= 10.
y /= 10.
r = np.sqrt(x*x+y*y)
z = 10*np.sin(r)/(r+0.01)
levels = [-4, -3, -2, -1, 1, 2, 3, 4]
plt.contourf(x, y, z, levels=levels, extend='both', cmap=cm.jet)
levels = [-1, 1]
plt.contourf(x, y, z, levels=levels, colors='w')
plt.savefig('contours.png')

Update 更新

In case you want more control, set the colors keyword in contourf to a tuple of matplotlib colors, with the same number of elements as you have levels (minus 1: the colors correspond to the intervals between your level boundaries). 如果您想要更多控制,请将contourfcolors关键字设置为matplotlib颜色的元组,其元素数量与您的级别相同(减1:颜色对应于级别边界之间的间隔)。 Then, you don't need to overplot a separate contour, and your colorbar is also correct: 然后,您不需要绘制单独的轮廓, 并且您的颜色条也是正确的:

# same as before
levels = [-4, -3, -2, -1, 1, 2, 3, 4]
plt.contourf(x, y, z, levels=levels, extend='both', colors=('#ff0000', '#ff9900', '#999900', 'w', '#009999', '#0099ff', '#0000ff'))
plt.savefig('contours.png')

Even nicer perhaps is to define your own colormap, but then you'll likely run into the issue that you have to match your colormap exactly with your contour levels. 更好的可能是定义自己的色彩映射,但是你可能会遇到一个问题,你必须将色彩映射与你的轮廓水平完全匹配。 Which is the why, conveniently, colors keyword exists. 这就是为什么,方便地, colors关键字存在的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM