简体   繁体   English

如何使图像居中 matplotlib

[英]How to Center an Image matplotlib

I have a graph in matplotlib that I want to overlay an image onto.我在 matplotlib 中有一个图表,我想在上面叠加图像。 Currently I am doing so using OffsetImage:目前我正在使用 OffsetImage 这样做:

team_logo = (os.getcwd() + "\Team_Logos"'\\' + data['posteam'].iloc[0] + '.png')
team_logo = plt.imread(team_logo)
team_logo = OffsetImage(team_logo, zoom=0.50)
team_logo.set_offset((2800, 2800))
ax.add_artist(team_logo)

But instead of the team_logo.set_offset((2800, 2800)) line, I would like to have the image be centered.但我想让图像居中而不是team_logo.set_offset((2800, 2800))行。 I have images of varying sizes that I want to be using at different times, so manually changing the ((2800,2800) to different coordinates for each figure I create is not a good solution. I am also using plt.savefig() with dpi=400 for my final image.我有不同大小的图像,我想在不同的时间使用,所以手动将((2800,2800)更改为我创建的每个图形的不同坐标不是一个好的解决方案。我也在使用plt.savefig() dpi=400用于我的最终图像。

The actual graph itself is always a 120 by 53.3 graph (x by y), but for some reason OffsetImage has the overlaid image show up differently in plt.show() than in plt.savefig(), so I can't just use ((60,26.65)) .实际图形本身始终是 120 x 53.3 图形(x x y),但由于某种原因,OffsetImage 的叠加图像在 plt.show() 中的显示方式与 plt.savefig() 中的显示方式不同,所以我不能只使用((60,26.65))

Does anyone know if there is a way for me to center my image over my plot that is saved to an image?有谁知道我是否有办法将我的图像放在保存到图像的 plot 上? I don't have to use OffsetBox, if there is a better way.如果有更好的方法,我不必使用 OffsetBox。 Thanks!谢谢!

Based on this tutorial , the easiest is probably to use an AnnotationBbox:根据本教程,最简单的可能是使用 AnnotationBbox:

from matplotlib.offsetbox import OffsetImage, AnnotationBbox

img = plt.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Ada_Lovelace_color.svg/200px-Ada_Lovelace_color.svg.png', format='png')

fig, ax = plt.subplots()

imagebox = OffsetImage(img, zoom=0.4)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, (0.5, 0.5), xycoords='axes fraction',
                    bboxprops={'lw':0})

ax.add_artist(ab)

plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM