Search code examples
pythonmatplotlibinsertfiguresubplot

How to insert a figure (3x3 subplot) into a subplot in matplotlib python


I want to insert a 3x3 figure into a subplot. Here and here is shown a similar problem, but the solution seems not to work in case (I think).

Can anyone please provide some code (as simple as possible) in order to produce this:

enter image description here

I'd be glad if someone could help with that, thanks in advance. Any answer or comment would be appreciated.


Solution

  • I created a workaround solution using this answer. The part added by me is written below the line with a comment #. I admit this is not general and perfect, but still sufficient in my opinion to get the work done.

    import matplotlib.pyplot as plt
    import numpy as np
    
    def add_subplot_axes(ax, rect): # This is the function in the linked answer
        fig = plt.gcf()
        box = ax.get_position()
        width = box.width
        height = box.height
        inax_position  = ax.transAxes.transform(rect[0:2])
        transFigure = fig.transFigure.inverted()
        infig_position = transFigure.transform(inax_position)    
        x = infig_position[0]
        y = infig_position[1]
        width *= rect[2]
        height *= rect[3]  
        subax = fig.add_axes([x,y,width,height])
        x_labelsize = subax.get_xticklabels()[0].get_size()
        y_labelsize = subax.get_yticklabels()[0].get_size()
        x_labelsize *= rect[2]**0.5
        y_labelsize *= rect[3]**0.5
        subax.xaxis.set_tick_params(labelsize=x_labelsize)
        subax.yaxis.set_tick_params(labelsize=y_labelsize)
        return subax
    
    # Modified part below
    
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111)
    x_start, y_start = 0.4, 0.4
    for i in range(3):
        for j in range(3):
            rect = [x_start+0.2*i, y_start+0.2*j, 0.15, 0.15]
            ax_ = add_subplot_axes(ax,rect)
            ax_.tick_params(labelsize=6)
    plt.show()
    

    enter image description here