Search code examples
pythonmatplotlibsavejupyter-notebookaxes

Saving matplotlib figure with add_axes


I'm trying to save a figure with an extra image on top. However Python only saves the bottom figure. I have:

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)

ax.plot(...)
...

ax_im = fig.add_axes([0.1, 1.0, 1, 1])
ax_im.set_xticks([])
ax_im.set_yticks([])

ax.imshow(...)
...

fig.savefig('image.png')

and Matplotlib only saves the figure related to the ax axis. In the iPython notebook the output is fine, it shows both figures, So, I don't know whats happening.


Solution

  • Try something like this

    ax_im = fig.add_axes([0.1, 0.2, 0.5, 0.5], label='axes1')
    

    The explanation is that your second parameter to add_axes is 1.0. This specifies the bottom ot the Axes at the top of the figure.

    Following example works for me:

    import pylab as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(212)
    
    ax.plot(range(3))
    
    ax_im = fig.add_axes([0.3, 0.5, 0.5, 0.4])
    ax_im.set_xticks([])
    ax_im.set_yticks([])
    
    plt.show()
    

    or even easier, use add_subplot twice:

    import pylab as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(212)
    
    ax.plot(range(3))
    
    ax_im = fig.add_subplot(211)
    ax_im.plot(range(3), 'o--')
    ax_im.set_xticks([])
    ax_im.set_yticks([])
    
    plt.show()