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?

j-i-l
  • 10,281
  • 3
  • 53
  • 70
Bob
  • 10,741
  • 27
  • 89
  • 143
  • `plt.savefig` saves the current figure and as long as you don't create a new figure it will add everything to the same, thus the superposition. – j-i-l Aug 13 '14 at 20:56
  • possible duplicate of [How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?](http://stackoverflow.com/questions/6916978/how-do-i-tell-matplotlib-to-create-a-second-new-plot-then-later-plot-on-the-o) – j-i-l Aug 13 '14 at 21:40

1 Answers1

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.

j-i-l
  • 10,281
  • 3
  • 53
  • 70
  • 2
    @Bob instead of `ax.plot()` write `ax.imshow(...)`. – j-i-l Aug 13 '14 at 21:46
  • for some reasons, I'm not getting a nice white color corresponding to the zero elements. is it a jpeg issue? – Bob Aug 14 '14 at 04:12
  • @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: http://matplotlib.org/examples/color/colormaps_reference.html – j-i-l Aug 14 '14 at 10:53
  • @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. ;) – j-i-l Aug 14 '14 at 10:55