Matplotlib 自动放置水印

jfr*_*ied 4 python matplotlib

我正在尝试编写一个函数来自动在我的数字右下角放置水印。到目前为止,这是我的功能。

from PIL import Image
import matplotlib.pyplot as plt

def watermark(fig, ax):

    """ Place watermark in bottom right of figure. """

    # Get the pixel dimensions of the figure
    width, height = fig.get_size_inches()*fig.dpi

    # Import logo and scale accordingly
    img = Image.open('logo.png')
    wm_width = int(width/4) # make the watermark 1/4 of the figure size
    scaling = (wm_width / float(img.size[0]))
    wm_height = int(float(img.size[1])*float(scaling))
    img = img.resize((wm_width, wm_height), Image.ANTIALIAS)

    # Place the watermark in the lower right of the figure
    xpos = ax.transAxes.transform((0.7,0))[0]
    ypos = ax.transAxes.transform((0.7,0))[1]
    plt.figimage(img, xpos, ypos, alpha=.25, zorder=1)
Run Code Online (Sandbox Code Playgroud)

问题是,当我向任一轴添加标签时,水印的位置会发生变化。例如,添加ax.set_xlabel('x-label', rotation=45)会显着改变水印位置。这似乎是因为水印的位置是相对于整个图形(例如绘图和轴区域),但是函数 get_size_inches() 只计算绘图区域(例如不包括轴区域)。

有没有办法获得整个图形的像素尺寸(例如,包括轴区域)或其他简单的解决方法。

提前致谢。

Imp*_*est 7

您可能想要使用一个AnchoredOffsetbox放置OffsetImage. 优点是您可以使用loc=4参数将 Offsetbox 放置在轴的右下角(就像图例的情况一样)。

from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.offsetbox import ( OffsetImage,AnchoredOffsetbox)


def watermark2(ax):
    img = Image.open('house.png')
    width, height = ax.figure.get_size_inches()*fig.dpi
    wm_width = int(width/4) # make the watermark 1/4 of the figure size
    scaling = (wm_width / float(img.size[0]))
    wm_height = int(float(img.size[1])*float(scaling))
    img = img.resize((wm_width, wm_height), Image.ANTIALIAS)

    imagebox = OffsetImage(img, zoom=1, alpha=0.2)
    imagebox.image.axes = ax

    ao = AnchoredOffsetbox(4, pad=0.01, borderpad=0, child=imagebox)
    ao.patch.set_alpha(0)
    ax.add_artist(ao)

fig, ax = plt.subplots()
ax.plot([1,2,3,4], [1,3,4.5,5])

watermark2(ax)
ax.set_xlabel("some xlabel")
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明