将 AstroPy 与 matplotlib 结合使用,由于使用了 plt.colorbar(),我收到一条警告,要求首先调用 grid(False)

jke*_*s99 6 python matplotlib astropy

尝试从 AstroPy:docs 运行此代码

    import matplotlib.pyplot as plt
    from astropy.visualization import astropy_mpl_style
    plt.style.use(astropy_mpl_style)
    
    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()
Run Code Online (Sandbox Code Playgroud)

我收到警告:

第 19 行 plt.colorbar() MatplotlibDeprecationWarning:自 3.5 起,pcolor() 和 pcolormesh() 自动删除网格已被弃用,并将在两个小版本后删除;请先调用 grid(False) 。

我尝试调用 plt.grid(False),但继续收到此警告/错误。有谁知道如何解决这个问题?

lan*_*ane 3

对于可能偶然发现此问题的用户,请搜索 Matplotlib 3.5 弃用警告消息。任何具有axes.gridTrue 的样式都可能触发此问题。一般来说,它可以被覆盖,plt.rcParams['axes.grid'] = False 但需要注意设置的位置和时间。

更新 1/19/2022

我已向 astropy 提交了有关此警告消息的错误报告。请参阅GitHub 问题

更新 1/26/2022

Matplotlib 已在matplotlib/matplotlib#22285中修复了此问题。我已经在 Matplotlib 3.6 的开发版本中确认该警告不再出现在相关代码中。

从问题出发解决问题

问题是astropy_mpl_style网格默认打开,这会触发一条关于在 Matplotlib 版本 3.5 中调用 plt.colorbar() 之前调用 plt.grid(False) 的弃用警告消息。尽管按照提示执行,但仍会出现此警告消息,因为样式优先于函数调用。

一种解决方法是覆盖 astropy_mpl_style 网格设置并防止网格在调用之前打开plt.colorbar()

astropy_mpl_style['axes.grid'] = False
Run Code Online (Sandbox Code Playgroud)

以下是它如何折叠到代码中以防止来自 Matplotlib 版本 3.5 的警告消息

import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
astropy_mpl_style['axes.grid'] = False
plt.style.use(astropy_mpl_style)

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()
Run Code Online (Sandbox Code Playgroud)