You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python绘制的Contour Plot添加Colorbar?

如何给Contour Plot添加Colorbar

你直接调用plt.colorbar()失败的核心原因是:colorbar需要明确关联到contourf生成的绘图对象。ax.contourf()会返回一个QuadContourSet实例,必须把这个实例传给colorbar才能正确创建颜色条。

修正后的代码

import numpy as np
import matplotlib.pyplot as plt
import xarray as xr

data = xr.open_dataset('mypath/data.nc')  

lat = np.array(data['latitude'][:])
lon = np.array(data['longitude'][:])
u = np.array(data['u'][:])
u = u.reshape(len(lat), len(lon))

fig, ax = plt.subplots(1,1,figsize=(8, 6))
X,Y = np.meshgrid(lon, lat)
# 捕获contourf的返回对象
contour_plot = ax.contourf(X, Y, u)
# 基于该对象创建colorbar,指定关联的轴更规范
fig.colorbar(contour_plot, ax=ax)

plt.show()  # 加上显示图像的语句

额外优化:利用xarray简化代码

你不需要手动把xarray数据转成numpy数组,xarray支持直接和matplotlib交互,简化后的代码如下:

import matplotlib.pyplot as plt
import xarray as xr

data = xr.open_dataset('mypath/data.nc')  

fig, ax = plt.subplots(1,1,figsize=(8, 6))
# 直接用xarray的plot方法,自动处理坐标和colorbar
data['u'].plot.contourf(ax=ax)

plt.show()

内容的提问来源于stack exchange,提问作者s28

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 09:09:58