如何更改图形中轴的单位?

问题描述 投票:1回答:1

我正在用matplotlib文件中的.fits来绘制一些星系速度的图。问题在于图中的轴以像素为单位显示了银河系的大小,我想将它们显示为Declination和RightAcension(以角度为单位)。我已经知道每个像素的大小为0.396弧秒。如何在X和Y轴上将像素转换为弧秒?

代码如下:

##############################################################################
# Generally the image information is located in the Primary HDU, also known
# as extension 0. Here, we use `astropy.io.fits.getdata()` to read the image
# data from this first extension using the keyword argument ``ext=0``:

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

##############################################################################
# The data is now stored as a 2D numpy array. Print the dimensions using the
# shape attribute:

print(image_data.shape)

##############################################################################
# Display the image data:

fig = plt.figure()
plt.imshow(image_data, cmap='Spectral_r', origin='lower', vmin=-maior_pixel, vmax=maior_pixel)
plt.colorbar()

fig.suptitle(f'{gals_header["MANGAID"]}', fontsize=20, fontweight='bold')

ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('RC')

ax.set_xlabel('pixelsx')
ax.set_ylabel('pixelsy')

还有比这更多的代码,但是我只想显示我认为是相关部分的内容(如有必要,我可以将其更多地放在注释中)。该代码基于此链接中的示例代码:https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py

[我已经尝试了Axes.convert_xunits和某些pyplot.axes函数之类的东西,但没有任何效果(或者我只是想不出如何正确使用它们)。

That is how the Image is currently

有人可以帮忙吗?预先谢谢你。

python matplotlib figure axes fits
1个回答
1
投票

您可以使用plt.FuncFormatter对象将所需的任何内容用作刻度标签。

这里是一个示例(确实是一个非常愚蠢的示例,请参阅出色的Matplotlib文档以获取详细信息。

import matplotlib.pyplot as plt
from numpy import arange

img = arange(21*21).reshape(21,21)

ax = plt.axes()
plt.imshow(img, origin='lower')
ax.xaxis.set_major_formatter(
    plt.FuncFormatter(lambda x, pos: "$\\frac{%d}{20}$"%(200+x**2)))

enter image description here

每个轴都有一个major_formatter,用于生成刻度线标签。

格式化程序必须是从Formatter继承的类的实例,在上面我们使用了FuncFormatter

要初始化FuncFormatter,我们将其传递给格式函数,我们必须使用以下required特性进行定义

  • 具有两个输入,xposx是要格式化的横坐标(或纵坐标),而可以安全地忽略pos
  • 返回要用作标签的字符串。

在该示例中,该函数已使用lambda语法进行了现场定义,其要旨是格式字符串("$\\frac{%d}{20}$"%(200+x**2)),该格式字符串的形式为横坐标的LaTeX分数,您可以参见上图。

据我所知,pos参数仅在某些方法中使用,例如

In [69]: ff = plt.FuncFormatter(lambda x, pos: "%r ፨ %05.2f"%(pos,x))

In [70]: ff.format_ticks((0,4,8,12))
Out[70]: ['0 ፨ 00.00', '1 ፨ 04.00', '2 ፨ 08.00', '3 ፨ 12.00']

但是通常,您可以忽略函数主体中的pos参数。

© www.soinside.com 2019 - 2024. All rights reserved.