【问题标题】:How do I change the axes' units in a figure?如何更改图中轴的单位?
【发布时间】:2020-04-14 04:58:23
【问题描述】:

我正在用matplotlib,从一些.fits 文件中制作一些星系速度的数字。问题是图中的轴以像素为单位显示了银河系的大小,我想将它们显示为偏角和 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_xunitspyplot.axes 之类的一些功能,但没有任何效果(或者我只是不知道如何正确使用它们)。

That is how the Image is currently

有人可以帮忙吗?提前谢谢你。

【问题讨论】:

    标签: python matplotlib figure axes fits


    【解决方案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)))
    

    每个轴都有一个major_formatter,负责生成刻度标签。

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

    要初始化FuncFormatter,我们向它传递一个格式化函数,我们必须使用以下必需特征来定义该函数

    • 有两个输入,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 参数。

    【讨论】:

    • 非常感谢您的帮助。我最终想出了另一种方法,我将在下面描述它的答案。但是在我这样做的方式中,我无法用刻度显示轴,而只能用网格显示。在这个项目中,网格不是问题。但我肯定会在进一步的代码中使用您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2019-12-02
    • 2018-01-11
    • 2018-11-30
    • 2021-09-14
    相关资源
    最近更新 更多