python contourf色阶_python – pyplot.contourf如何从色彩图中选择颜色?

本文探讨了如何在使用matplotlib的pcolormesh时,使颜色与contourf图匹配的问题。通过调整颜色间隔和使用特定的色彩映射函数,实现了颜色的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我一直在使用from_levels_and_colors函数,因此我可以在pcolormesh图上使用扩展颜色条,类似于contourf.这是我的示例contourf plot:

import numpy as np

import matplotlib.pyplot as plt

a = np.arange(12)[:,np.newaxis] * np.ones(8)

levels = np.arange(1.5, 10, 2)

plt.contourf(a, cmap='RdYlBu', levels=levels, extend='both')

plt.colorbar()

为了产生类似的pcolormesh图,我需要提供一系列颜色,所以我有:

from matplotlib.colors import from_levels_and_colors

n_colors = len(levels) + 1

cmap = plt.get_cmap('RdYlBu', n_colors)

colors = cmap(range(cmap.N))

cmap, norm = from_levels_and_colors(levels, colors, extend='both')

plt.pcolormesh(a, cmap=cmap, norm=norm)

plt.colorbar()

pcolormesh中的中间四种颜色比contourf中的颜色浅.我如何选择它们

``` import os import matplotlib.ticker as mticker import netCDF4 as nc import matplotlib.path as mpath import cmaps import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl import cartopy.crs as ccrs import cartopy.feature as cfeature from netCDF4 import Dataset from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import regionmask import cartopy.io.shapereader as shpreader #-------------------------------- 1. 读取NC文件 --------------------------------# nc_file = r"D:\biyelunwen\data\sat_swe_flow.nc" ds = Dataset(nc_file) # 假设数据变量名为'snow',经纬度为'lon'和'lat' # 请根据实际NC文件结构调整变量名称和维度顺序 lon = ds.variables['longitude'][:] # 读取经度数组 lat = ds.variables['latitude'][:] # 读取纬度数组 data1 = ds.variables['flow_sat_to_swe'][:] # 读取数据,假设为三维数组(time, lat, lon) data2 = ds.variables['flow_swe_to_sat'][:] # 示例:取第一个时间步和创建示例数据 dss = np.array([data1, data2]) # 生成两个数据层用于绘演示 #-------------------------------- 2. 形参数设置 --------------------------------# mpl.rcParams["font.family"] = 'Arial' mpl.rcParams["mathtext.fontset"] = 'cm' mpl.rcParams["font.size"] = 12 mpl.rcParams["axes.linewidth"] = 1 proj = ccrs.NorthPolarStereo(central_longitude=0) # 北半球极地投影 leftlon, rightlon, lowerlat, upperlat = (-180, 180, 20, 90) img_extent = [leftlon, rightlon, lowerlat, upperlat] #-------------------------------- 3. 创建画布和子 --------------------------------# fig = plt.figure(figsize=(14,6), dpi=600) title = np.array(['(a) inf from SAT to SWE', '(b) inf from SWE to SAT']).reshape(2, 1) for j in range(2): # 设置子位置 left = 0.1 + j * 0.25 ax = fig.add_axes([left, 0.5, 0.35, 0.4], projection=proj) # 添加标题 ax.set_title(f'{title[j, 0]}', loc='center', fontsize=14) #-------------------------------- 4. 设置地要素 --------------------------------# # 添加网格线 gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='grey', linestyle='--', xlocs=[-180, -90, 0, 90, 180]) gl.xformatter = LONGITUDE_FORMATTER # 经度格式 gl.yformatter = LATITUDE_FORMATTER # 纬度格式 gl.rotate_labels = False # 禁止旋转标签 ax.set_extent(img_extent, ccrs.PlateCarree()) # 设置地范围 ax.add_feature(cfeature.COASTLINE.with_scale('110m')) # 添加海岸线 #-------------------------------- 5. 裁剪圆形边界 --------------------------------# theta = np.linspace(0, 2*np.pi, 100) center, radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mpath.Path(verts * radius + center) ax.set_boundary(circle, transform=ax.transAxes) #-------------------------------- 6. 添加青藏高原轮廓 --------------------------------# tp_shape = shpreader.Reader(r"D:\biyelunwen\TPBoundary_new(2021)\TPBoundary_new(2021).shp").geometries() ax.add_geometries(tp_shape, crs=ccrs.PlateCarree(), edgecolor='red', facecolor='none', linewidth=1.5, linestyle='--', alpha=0.8) #-------------------------------- 7. 数据处理与可视化 --------------------------------# # 创建二维经纬度网格 lon2d, lat2d = np.meshgrid(lon, lat) # 绘制填 pcm = ax.contourf(lon, lat, transform=ccrs.PlateCarree(), cmap='RdBu_r', levels=np.arange(-4, 4, 0.4), extend='neither') #-------------------------------- 8. 添加颜色条 --------------------------------# cax = fig.add_axes([0.2, 0.4, 0.4, 0.03]) # 调整颜色条位置 cbar = fig.colorbar(pcm, cax=cax, orientation='horizontal') cbar.set_label('Snow Depth (m)') # 设置颜色条标签 plt.show()```如何画出data1,data2的北极极地投影
最新发布
03-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值