3

I am trying to generate different figures with matplotlib:

import matplotlib.pyplot as plt

for item in item_list:
    plt.imshow(item)
    plt.grid(True)
    # generate id
    plt.savefig(filename + id)
    plt.close()

The loop does generate a number of files but they seem to show the superposition of different figures, whereas, if I plot the items one by one they look very different.

How do I make sure each item is plotted independently and saved to file?

2

1 Answer 1

3

You need to either create a new figure object, or clear the axis.

Example code clearing the axis:

import matplotlib.pyplot as plt
y_data = [[1,1],[2,2],[3,3]]  #just some dummy data
x = [0,1]  
fig,ax = plt.subplots()
for y in y_data:   
    #generate id   
    ax.cla()  #clear the axis
    ax.plot([0,1],y)
    fig.savefig(filename + id)

Example with new figure object:

import matplotlib.pyplot as plt
y_data = [[1,1],[2,2],[3,3]]  #just some dummy data
x = [0,1]
for y in y_data:  
    #generate id  
    fig,ax = plt.subplots()  #create a new figure
    ax.plot(x,y)
    fig.savefig(filename + id)

Hope this helps to get you started.

Sign up to request clarification or add additional context in comments.

4 Comments

@Bob instead of ax.plot() write ax.imshow(...).
for some reasons, I'm not getting a nice white color corresponding to the zero elements. is it a jpeg issue?
@Bob Hm, it's hard to tell not knowing more details. I find it unlikely that the jpeg is the issue. It probably depends on the colormap you are using. Here is a link I found helpful in this respect: matplotlib.org/examples/color/colormaps_reference.html
@Bob If the problem persists, I suggest you browse SO for a solution or open a new question if you don't find what you are looking for. Also consider accepting my answer for this question. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.