2017-02-16 78 views
0

我想用matplotlib生成一个多图,并在每个子图的角落中嵌入图像。Matplotlib:在几个子图中嵌入图像()

我已经能够使用following example of the matplotlib documentation(代码如下)在(单个)情节图中嵌入图像。

我现在试图将图像嵌入到一系列子图的每一个的角落。我似乎无法找到类似于我之前示例所依赖的图的add_axes()的功能。

我怎样才能达到理想的布局?

import pylab as plt 
from numpy import linspace 
from matplotlib.cbook import get_sample_data 
from scipy.misc import imread 

xs = linspace(0, 1, 100) 

def single_plot(): 
    fig, ax = plt.subplots() 
    ax.plot(xs, xs**2) 

    fn = get_sample_data("grace_hopper.png", asfileobj=False) 
    image_axis = fig.add_axes([0.65, 0.70, 0.3, 0.2], anchor='NE', zorder=10) 
    image_axis.imshow(imread(fn)) 

    plt.show() 
    plt.clf() 

def multi_plot(): 
    fig, axes = plt.subplots(4) 
    for axis in axes: 
     axis.plot(xs, xs**2) 
     # How to draw the same image as before in the corner of each subplot ? 
    plt.show() 

if __name__ == '__main__': 
    single_plot() 
    multi_plot() 

回答

2

您可以使用相同的方法在多个子图上叠加图像。轴位置必须为您要覆盖的每个图像相对于整个图形定义。以下是使用您的代码和Matplotlib文档的简单示例。

def multi_plot(): 
    fig, axes = plt.subplots(4, 1, figsize=(8, 10)) 
    fn = get_sample_data("grace_hopper.png", asfileobj=False) 
    image = plt.imread(fn) 
    x = 0 
    for axis in axes: 
     axis.plot(xs, xs**2) 

     # [left, bottom, width, height] 
     image_axis = fig.add_axes([0.125, 0.25 + x, 0.15, 0.65], 
           zorder=10, anchor="N") 
     image_axis.imshow(image) 
     image_axis.axis('off') 
     x -= 0.209 

    plt.show() 

我已选择增量减少新轴相对于图底部的位置。您还可以为要添加的每个图像叠加指定确切的位置。

上面的代码产生一个情节,看起来像这样: Image Overlay Subplots

+0

@伯特兰 - 卡隆如果答案解决你的问题,请考虑[接受它作为一个解决方案(http://stackoverflow.com/help /有人-答案)。 – Brian