python放大图形中部分内容_python – 在matplotlib中缩放图像而不更改轴

有一个

watermark example与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’,数组im的[0,0]索引位于范围的左上角.如果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和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()

你可能感兴趣的:(python放大图形中部分内容)