【问题标题】:How to center a plotted image?如何使绘制的图像居中?
【发布时间】:2026-02-11 18:20:05
【问题描述】:

我没有发布整个代码,因为其中大部分都不相关。我只需要帮助将图像居中。

ra_new2=cat['ra'][z&lmass&ra&dec][i]
dec_new2=cat['dec'][z&lmass&ra&dec][i]
target_pixel_x = ((ra_new2-ra_ref)/(pixel_size_x))+reference_pixel_x     
target_pixel_y = ((dec_new2-dec_ref)/(pixel_size_y))+reference_pixel_y    
fig = plt.figure(figsize=(5.,5.))
galaxy=plt.imshow(img[target_pixel_x-200:target_pixel_x+200, target_pixel_y- 
200:target_pixel_y+200], vmin=-0.01, vmax=0.1, cmap='Greys')
plt.show()

plt.imshow 是我想要居中的。它正确地绘制,但情节在左下角。如何将它放在图形窗口的中间?我需要这个,以便我可以调整缩放的参数。

【问题讨论】:

    标签: python graph plot centering


    【解决方案1】:

    您可以使用extent=(left, right, bottom, top) 参数告诉imshow 您想要图像的位置。 leftrightbottomtop 的值在数据坐标中。

    例如,

    import matplotlib.pyplot as plt
    import matplotlib.image as mimage
    import matplotlib.cbook as cbook
    datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
    im = mimage.imread(datafile)
    fig, ax = plt.subplots(figsize=(5.,5.))
    myaximage = ax.imshow(im,
                          aspect='auto',
                          extent=(20, 80, 20, 80),
                          alpha=0.5)
    ax.plot(range(100))
    plt.show()
    

    生产

    【讨论】:

    • extent 参数用于 x 范围和 y 范围。