Python 使用matplotlib figure.figimage在图形中心设置图像
我试图在matplotlib图形的中心设置一个图像,本质上是一个水印。我希望图像的中心位于图形的中心。问题似乎是图形大小和dpi(10“x 10”和960 x 960像素)与保存的图像(像素尺寸为610 x 623)之间存在差异。当我在960/2960/2处通过Figure.figimage添加图像时,这是完成图像的偏心。下面是我的代码和示例图像 创建绘图:Python 使用matplotlib figure.figimage在图形中心设置图像,python,image,matplotlib,figure,Python,Image,Matplotlib,Figure,我试图在matplotlib图形的中心设置一个图像,本质上是一个水印。我希望图像的中心位于图形的中心。问题似乎是图形大小和dpi(10“x 10”和960 x 960像素)与保存的图像(像素尺寸为610 x 623)之间存在差异。当我在960/2960/2处通过Figure.figimage添加图像时,这是完成图像的偏心。下面是我的代码和示例图像 创建绘图: f, ax = plt.subplots(1, figsize=(10,10)) f.set_facecolor((1,1,1)) ax.
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
如何以任何比例知道已保存图像的尺寸?或者为什么完成的图像实际上不是10x10”和960x960像素?谢谢。为了从10“x10”的绘图中获得960x960像素的图形,您还必须将
plt.savefig()中的dpi
关键字设置为96 dpi。例如:
plt.savefig('im.png', dpi=96)
输出正确:
当使用例如72<代码>dpi时,结果是:
为了从10“x10”的绘图中获得960x960像素的图形,您还必须将plt.savefig()
中的dpi
关键字设置为96 dpi。例如:
plt.savefig('im.png', dpi=96)
输出正确:
当使用例如72<代码>dpi时,结果是:
适用于png图像,但我必须将其保存为pdf格式,并且使用pdf.savefig(f,dpi=96)
不起作用。它看起来仍然像我的第一张图像。这适用于png图像,但我必须将其保存为pdf格式,并且使用pdf.savefig(f,dpi=96)
不起作用。它看起来仍然像我的第一张图像。