有一个与 matplotlib 一起分发的水印示例,有点类似。从该代码开始,我们可以进行如下修改:
用于ax.imshow
首先绘制图像。我这样做是因为extent
参数会影响ax
. 由于我们希望最终范围由 控制plt.plot(...)
,所以我们把它放在最后。
myaximage = ax.imshow(im, aspect='auto', extent=(1,15,0.3,0.7), alpha=0.5, origin='upper', zorder=-1)
代替extent=myaxe.axis()
,用于extent
控制图像的位置和大小。extent=(1,15,0.3,0.7)
将图像放置在(1, 0.3)
左下角和右上角的矩形中(15, 0.7)
。
使用origin='upper'
,[0,0]
数组的索引im
放置在范围的左上角。它将被放置在origin='lower'
左下角。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.image as image
np.random.seed(1)
datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
im = image.imread(datafile)
fig, ax= plt.subplots()
myaximage = ax.imshow(im, aspect='auto', extent=(1,15,0.3,0.7), alpha=0.5, zorder=-1)
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=1.0, mfc='orange')
ax.grid()
plt.show()
如果要扩展图像并将其剪辑到绘图的范围内,则可能还需要使用ax.set_xlim
and ax.set_ylim
:
myaximage = ax.imshow(im, aspect='auto', extent=(-1,25,0.3,0.7), alpha=0.5, zorder=-1,
origin='upper')
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=1.0, mfc='orange')
ax.set_xlim(0,20)
ax.set_ylim(0,1)
或者,为了获得更多控制,您可以使用以下命令将图像剪辑到任意路径myaximage.set_clip_path
:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.patches as patches
np.random.seed(1)
datafile = cbook.get_sample_data('logo2.png', asfileobj=False)
im = image.imread(datafile)
fig, ax= plt.subplots()
myaximage = ax.imshow(im, aspect='auto', extent=(-5,25,0.3,0.7),
alpha=0.5, origin='upper',
zorder=-2)
# patch = patches.Circle((300,300), radius=100)
patch = patches.Polygon([[5, 0.4], [15, 0.4], [15, 0.6], [5, 0.6]], closed=True,
transform=ax.transData)
myaximage.set_clip_path(patch)
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=1.0, mfc='orange',
zorder=-1)
ax.set_xlim(0, 20)
ax.set_ylim(0, 1)
plt.show()