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

使用AstroPy搭配matplotlib调用plt.colorbar()出现grid警告如何解决

问题根因

该警告由astropy_mpl_style默认开启全局坐标轴网格配置触发:matplotlib 3.5+版本废弃了colorbar内部调用pcolormesh时自动移除网格的逻辑,你手动调用plt.grid(False)未生效通常是因为调用时机晚于样式加载,或未作用到imshow对应的坐标轴对象上。

解决方法

方法1:全局关闭网格(最推荐,适配天文绘图常用场景)

加载astropy样式后立刻覆盖网格配置,从根源避免触发警告,修改后完整代码如下:

import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
# 新增行,覆盖样式默认的网格开启配置
plt.rcParams['axes.grid'] = False

from astropy.utils.data import get_pkg_data_filename
from astropy.io import fits

image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
fits.info(image_file)

image_data = fits.getdata(image_file, ext=0)

print(image_data.shape)

plt.figure()
plt.imshow(image_data, cmap='gray')

plt.colorbar()

方法2:仅关闭当前绘图的网格

如果需要保留其他场景的网格显示,可在生成当前图的坐标轴后单独关闭网格:
在plt.imshow()代码行后新增:

plt.gca().grid(False)

方法3:临时过滤指定警告

如果不想修改样式配置,可直接过滤该特定废弃警告,在代码开头添加如下内容即可:

import warnings
import matplotlib
warnings.filterwarnings(
    "ignore",
    category=matplotlib.MatplotlibDeprecationWarning,
    message="Auto-removal of grids by pcolor"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:36:08