我试着设置一个图像,一个水印,在matplotlib图形的中心。我希望图像的中心在图形的中心。问题似乎是图形大小和10”x 10”和960 x 960像素的dpi与保存的图像(像素大小为610 x 623)之间的差异。当我通过图形添加图像时。figimage在960/2,960/2,这是完成的图像偏心。我的代码和示例图像如下。
创建绘图:
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])
添加图像:
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
x1c 0d1x我怎样才能知道保存的图像在任何比例下的尺寸?或者为什么完成的图像实际上不是10 x10”和960 x960 pixels?谢谢。
2条答案
按热度按时间ct2axkht1#
为了从10“x10”图中得到960x960像素的图形,您还必须将
plt.savefig()
中的dpi
关键字设置为96 dpi。输出正确:
而对于例如72
dpi
,结果是:kgqe7b3p2#
对你的功能做些小小的调整对我很有效...