将matplotlib colormap居中到特定值上

slsn1g29  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(98)

我正在使用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()

字符串
使用默认值绘图:
x1c 0d1x的数据
设置vmin、vmax后绘图:


g6ll5ycj

g6ll5ycj1#

你可以手动设置你想要显示的水平。只要你在零的左边和右边有相同的间隔,这就能很好地工作。

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()


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

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



如果级别不相等,则需要指定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)



缺点是你的分辨率不高,因此你可以使用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()



要更改颜色条上的ticklabels,使其不同于级别,或者如果它们太分散,您可以使用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()


相关问题