Reputation: 499
I have a graph in matplotlib that I want to overlay an image onto. Currently I am doing so using 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. 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.
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))
.
Does anyone know if there is a way for me to center my image over my plot that is saved to an image? I don't have to use OffsetBox, if there is a better way. Thanks!
Upvotes: 0
Views: 2246
Reputation: 40697
Based on this tutorial, the easiest is probably to use an 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()
Upvotes: 1