I'm trying to set an image, a watermark essentially, at the center of a matplotlib Figure. I would like the center of the image to be at the center of the figure. The problem appears to be a difference between the figure size and dpi of 10" x 10" and 960 x 960 pixels and the saved image which has pixel dimensions of 610 x 623. When I add the image via Figure.figimage at 960/2, 960/2, that is offcenter of the finished image. My code and example image are below.
Creating the plot:
f, ax = plt.subplots(1, figsize=(10,10))
f.set_facecolor((1,1,1))
ax.set_title('{} Reflection Integrated Intensity vs Max Intensity of {}'.format(refl, rcmap.sample_number), size=14)
f = add_logo(f, '/home/zeppelin_d/Desktop/company.com_logo.png',x_frac=0.5, y_frac=0.5, scale=0.5, alpha=0.15)
ax = sns.regplot(x='z', y='int_int', data=df, scatter_kws={'alpha':0.4})
ax.set_xlabel('{} Max Intensity'.format(refl), size=14)
ax.set_ylabel('{} Integrated Intensity'.format(refl, size=14))
ax.set_xlim([0,max(df['z']) * 1.05])
ax.set_ylim([0,max(df['int_int']) * 1.05])
and adding the image:
def add_logo(f, path, x_frac=0.5, y_frac=0.5, scale=1, alpha=1):
"""
Add an image to the figure (not the axes)
f: a matplotlib figure instance.
path: the string path to the image to add to the figure.
x_frac: the fraction of the x dimension of the figure to set the offset to.
Must be a float.
y_frac: the fraction of the y dimension of the figure to set the offset to.
Must be a float.
scale: the float scale by which to multiply to the image pixel dimensions.
alpha: the alpha to set the inserted image to
Set the figure dpi to the same as screen dpi.
Use this like:
f = add_logo(f, 'mah_business_logo.png',x_frac=0.5, y_frac=0.5, scale=0.5, alpha=0.15)
for setting a watermark. This should put the center of the image in the center of the
figure at half it's original size.
"""
assert type(x_frac) == float and type(y_frac) == float, "x_frac and y_frac must be floats."
im = Image.open(path)
f.set_dpi(96)
im.thumbnail((int(im.size[0] * scale), int(im.size[1] * scale)), Image.ANTIALIAS)
img_x, img_y = im.size[0], im.size[1]
x_offset = int((f.bbox.xmax * x_frac - img_x/2))
y_offset = int((f.bbox.ymax * y_frac - img_y/2))
f.figimage(im, xo=x_offset, yo=y_offset, origin='upper', zorder=10, alpha=alpha)
return f
How can I know the dimensions of the saved image at any scale? Or why is the finished image not actually 10x10" and 960x960pixels? Thanks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.