如何用Astropy与Matplotlib为赤纬轴(Y轴)正值添加+符号?
为天图赤纬轴(Y轴)正值添加“+”符号的解决方案
问题背景
我使用Python的astropy、matplotlib、skyfield和astroquery制作天图,通过skyfield实现天空球面投影,利用astropy的WCS完成投影配置。需要为赤纬轴(Y轴)的正值添加“+”符号,方便公众用户清晰识别,但尝试以下方法均未成功:
- 使用
set_major_formatter('d')仅能配置小数格式,无法添加+号 - 尝试遍历刻度值,未实现预期效果
- 使用
matplotlib.ticker格式化器,因WCS投影特性无效
配置代码
import matplotlib.pyplot as plt import numpy as np from astropy.wcs import WCS fig = plt.figure(figsize=[600/96, 500/96]) plt.subplots_adjust(left=0.1, right=0.75, top=0.9, bottom=0.1) wcs = WCS(naxis=2) wcs.wcs.crpix = [1, 1] wcs.wcs.cdelt = np.array([-360 / np.pi, 360 / np.pi]) wcs.wcs.crval = [COORD.ra.deg, COORD.dec.deg] wcs.wcs.ctype = ["RA---STG", "DEC--STG"] ax = fig.add_subplot(111, projection=wcs) angle = np.pi - FOV / 360.0 * np.pi limit = np.sin(angle) / (1.0 - np.cos(angle)) ax.set_xlim(-limit, limit) ax.set_ylim(-limit, limit) ax.set_aspect('equal') ax.coords.grid(True, color='white', linestyle='dotted') ax.coords[0].set_axislabel(' ') ax.coords[1].set_axislabel(' ')
尝试过的格式化代码
ax.coords[1].set_major_formatter('d')
解决方案
由于astropy的WCS坐标轴基于wcsaxes实现,需自定义格式化函数来处理刻度显示:
def dec_formatter(value, pos): # 根据需求调整数值格式,这里以整数为例 if value > 0: return f"+{int(value)}" elif value == 0: return "0" else: return f"{int(value)}" # 为赤纬轴(索引1)应用自定义格式化器 ax.coords[1].set_major_formatter(dec_formatter)
说明
- 自定义函数接收刻度值
value和位置pos两个参数,返回格式化后的字符串 - 若需要保留小数位数,可修改返回格式,例如
f"+{value:.1f}"保留一位小数 - 该方法适配WCS投影的坐标系统,可正常显示带+号的正值赤纬刻度
内容的提问来源于stack exchange,提问作者Unix
相关产品推荐
相关产品推荐

