中心matplotlib色彩图上的特定值

时间:2018-03-14 16:24:54

标签: python python-3.x matplotlib colormap

我正在使用matplotlib colormap" seismic"并且希望将白色颜色设置为0.当我运行我的脚本而没有任何变化时,白色从0下降到-10。我尝试了设置vmin = -50,vmax = 50,但在这种情况下我完全失去了白色。有关如何实现这一目标的任何建议吗?

from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
nc = NetCDFFile('myfile.nc')
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time = nc.variables['time'][:]
hgt = nc.variables['hgt'][:]
map = Basemap(llcrnrlon=180.,llcrnrlat=0.,urcrnrlon=320.,urcrnrlat=80.)
lons,lats = np.meshgrid(lon,lat)
x,y = map(lons,lats)
cs = map.contourf(x,y,hgt[0],cmap='seismic')
cbar = plt.colorbar(cs, orientation='horizontal', shrink=0.5, 
cmap='seismic')
cbar.set_label('500mb Geopotential Height Anomalies(m)')
map.drawcoastlines()
map.drawparallels(np.arange(20,80,20),labels=[1,1,0,0], linewidth=0.5)
map.drawmeridians(np.arange(200,320,20),labels=[0,0,0,1], linewidth=0.5)
plt.show()`

Plot with defaults

Plot with vmin, vmax set

1 个答案:

答案 0 :(得分:2)

您可以设置要手动显示的级别。只要你的左边和右边的间隔相同,这就可以很好地工作。

levels = [-50,-40,-30,-20,-10,10,20,30,40,50]
ax.contourf(X,Y,Z, levels)

示例:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-6.3,6.3)
y = np.linspace(-3.1,3.1)
X,Y = np.meshgrid(x,y)
Z = -np.cos(X)*np.cos(Y)*45

levels = [-50,-40,-30,-20,-10,10,20,30,40,50]
fig, ax = plt.subplots(figsize=(4,2))
cont = ax.contourf(X,Y,Z,levels, cmap="seismic")
fig.colorbar(cont, orientation="horizontal")
plt.show()

enter image description here

或者,如果您希望颜色条与数据成比例,

fig.colorbar(cont, orientation="horizontal", spacing="proportional")

enter image description here

如果级别不相等,则需要指定vminvmax

levels = [-50,-40,-30,-20,-10,10,30,50,80,100]
cont = ax.contourf(X,Y,Z,levels, cmap="seismic", vmin=-50, vmax=50)

enter image description here

缺点是分辨率松散,因此您可以使用BoundaryNorm为不等间距的标签选择等间距的颜色。

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

x = np.linspace(-6.3,6.3)
y = np.linspace(-3.1,3.1)
X,Y = np.meshgrid(x,y)
Z = -np.cos(X)*np.cos(Y)*45

levels = [-50,-40,-30,-20,-10,10,30,50,80,100]
norm = matplotlib.colors.BoundaryNorm(levels, len(levels)-1)
fig, ax = plt.subplots(figsize=(4,2))
cont = ax.contourf(X,Y,Z,levels,cmap=plt.get_cmap("seismic",len(levels)-1), norm=norm)
fig.colorbar(cont, orientation="horizontal")
plt.show()

enter image description here

要更改颜色条上的刻度标签,使其不是级别,或者如果它们太过分,则可以使用ticks参数。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-6.3,6.3)
y = np.linspace(-3.1,3.1)
X,Y = np.meshgrid(x,y)
Z = -np.cos(X)*np.cos(Y)*45

levels = np.arange(-45,50,5)
levels = levels[levels!=0]
ticks=np.arange(-40,50,10)

fig, ax = plt.subplots(figsize=(4,2))
cont = ax.contourf(X,Y,Z,levels,cmap="seismic", spacing="proportional")
fig.colorbar(cont, orientation="horizontal", ticks=ticks, spacing="proportional")
plt.show()

enter image description here