简体   繁体   English

在图matplotlib中插入图像

[英]inset imshow within figure matplotlib

I'm trying to have an imshow plot inset into another in matplotlib. 我正在尝试在matplotlib中将一个imshow图插入另一个图中。

I have a figure that has an plot on top and an imshow on the bottom: 我有一个图,上面有一个图,下面有一个imshow:

fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
plt.plot()
ax2 = fig.add_subplot(2,1,2)
plt.imshow()

and then I have another figure, which also is comprised of a plot on top and an imshow below. 然后我有另一个图,它也由上图和下图显示。 I want this second figure to be inset into the top plot on the first figure. 我希望将第二个图插入第一个图的顶部图中。

I tried follow this example . 我试着按照这个例子 The code ran without an error but I had an empty axis in the position I wanted it. 代码运行时没有错误,但是我想要的位置有一个空轴。

My problem is just that I'm not sure where to put the plt.setp() command If that's what I am supposed to use. 我的问题是我不确定在哪里放置plt.setp()命令。

First, I don't think you can put a figure into a figure in matplotlib . 首先,我认为您不能在matplotlib中将图形放入图形中。 You will have to arrange your Axes objects (subplots) to achieve the look you want. 您必须安排您的Axes对象(子图)才能获得所需的外观。

The example you provided uses absolute positioning to do that. 您提供的示例使用绝对定位来做到这一点。 setp there is not related to positioning, though — it just removes axis ticks from insets. setp与定位无关,它只是从插图中删除了轴刻度。 An example of code that does what you want: 满足您需求的代码示例:

import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(0, 1)

xx, yy = numpy.meshgrid(x, x)
im = numpy.sin(xx) + numpy.cos(yy)**2


fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(x, x**2)
ax2 = fig.add_subplot(2,1,2)
ax2.imshow(im)

inset1 = fig.add_axes([.15, .72, .15, .15])
inset1.plot(x, x**2)
plt.setp(inset1, xticks=[], yticks=[])

inset2 = fig.add_axes([0.15, 0.55, .15, .15])
inset2.imshow(im)
plt.setp(inset2, xticks=[], yticks=[])

fig.savefig('tt.png')

在此处输入图片说明

Here the insets use explicit positioning with coordinates given in "figure units" (the whole figure has size 1 by 1). 在此,插图使用显式定位,坐标以“数字单位”给出(整个图形的尺寸为1乘1)。

Now, of course, there's plenty of room for improvement. 现在,当然,还有很大的改进空间。 You probably want the widths of your plots to be equal, so you'll have to: 您可能希望绘图的宽度相等,所以您必须:

  • specify the positioning of all subplots explicitly; 明确指定所有子图的位置; or 要么
  • play with aspect ratios; 玩纵横比; or 要么
  • use two GridSpec objects (this way you'll have the least amount of magic numbers and manual adjustment) 使用两个GridSpec对象(这样,您将拥有最少的幻数和手动调整)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM