AttributeError:“ NoneType”对象没有属性“ coords”

问题描述

我在python3中编译时遇到问题,代码为

import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
from astropy.coordinates import SkyCoord 
from astropy.coordinates import ICRS,Galactic,FK4,FK5  
from astropy.coordinates import Angle,Latitude,Longitude  
import astropy.units as u


filename = get_pkg_data_filename('jopi.fits')


hdu = fits.open(filename)[0]
wcs = WCS(hdu.header).celestial
wcs.wcs.crval = [0,0]
wcs.wcs.ctype = [ 'XOFFSET','YOFFSET' ]


fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(projection=wcs)
plt.imshow(hdu.data[0][0],origin='lower') 
lon = ax.coords[0]
lat = ax.coords[1]
lon.set_major_formatter('x')
lat.set_major_formatter('x')
lon.set_format_unit(u.milliarcsecond)
lat.set_format_unit(u.milliarcsecond)
ax.set_xlim(200,800)
ax.set_ylim(200,800)
ax.set_xlabel('Relative R.A ()')
ax.set_ylabel('Relative Dec ()')

我总是得到

lon = ax.coords [0] AttributeError:“ NoneType”对象没有属性 'coords'

是否缺少某些东西?

解决方法

这意味着ax变量的值为None。它不是您所期望的Axes对象。您可以通过一些基本的调试来确认这一点,例如在以下位置添加打印声明:

ax = fig.add_subplot(projection=wcs)

尽管我也建议您查看fig.add_subplot的代码。在IPython / Jupyter中,您可以键入fig.add_subplot??来查看此内容,并且该函数的代码的第一行(在文档字符串之后)是:

        if not len(args):
            return

(这是IMO令人困惑的功能)。

您需要按照here的说明向fig.add_subplot传递一些其他参数。

例如:

ax = fig.add_subplot(111,projection=wcs)

提供要处理的子图的布局和位置。

您可能会使用matplotlib Figure.add_subplot的位置参数的默认值为111,从而允许像您编写的代码工作:https://github.com/matplotlib/matplotlib/pull/13127

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...