Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: creating new figure and saving to file

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?

like image 428
Bob Avatar asked May 22 '26 05:05

Bob


1 Answers

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.

like image 175
jojo Avatar answered May 25 '26 10:05

jojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!