corinna
corinna

Reputation: 649

matplotlib: drawing simultaneously to different plots

Due to the 2nd answer of this question I supposed the following code

import matplotlib.pyplot as plt

for i1 in range(2):

    plt.figure(1)
    f, ax = plt.subplots()
    plt.plot((0,3), (2, 2), 'b')


    for i2 in range(2):
        plt.figure(2)
        f, ax = plt.subplots()
        plt.plot([1,2,3], [1,2,3], 'r')
        plt.savefig('foo_{}_bar_{}.jpg'.format(i2, i1))
        plt.close()

    plt.figure(1)
    plt.plot( [1,2,3],[1,2,3], 'r')

    plt.savefig('bar_{}.jpg'.format(i1))
    plt.close()

to create plots bar_0.jpg and bar_1.jpg showing a blue and a red line each.

However, figures look like

enter image description here

instead of

enter image description here

How can I achieve the desired behaviour? Note that plots foo_*.jpg have to be closed and saved during handling of the bar plots.

Upvotes: 1

Views: 1750

Answers (2)

M.T
M.T

Reputation: 5231

If unsure, better to make it explicit:

import matplotlib.pyplot as plt

for i1 in range(2):
    fig1,ax1 = plt.subplots()
    fig2,ax2 = plt.subplots()
    ax1.plot([0,4],[2,2],'b')

for i2 in range(2):
    ax2.plot([1,2,3],[1,2,3],'r')
    fig2.savefig('abc{}.png'.format(2*i1+i2))
    plt.figure(1)
    ax1.plot([1,2,3],[1,2,3],'r')

fig1.savefig('cba{}.png'.format(i1))

Upvotes: 2

rubenvb
rubenvb

Reputation: 76519

You're already saving the Axes objects, so instead of calling the PyPlot plot function (which draws on the last created or activated Axes), use the objects' plot function:

ax.plot(...)

If you then give both a different name, say ax1 and ax2, you can draw on the one you like without interfering with the other. All plt. commands also exist as an Axes member function, but sometimes the name changes (plt.xticks becomes ax.set_xticks for example). See the documentation of Axes for details.

To save to figures, use the Figure objects in the same way:

f.savefig(...)

This API type is only just coming to Matlab, FYI, and will probably replace the old-fashioned "draw on the last active plot" behaviour in the future. The object-oriented approach here is more flexible with minimal overhead, so I strongly recommend you use it everywhere.

Upvotes: 2

Related Questions