0

I am having issue saving plots to a folder. I want to store all of the plots created in a for loop to a folder that I previously created.

I tried using imsave() function as follows:

for p in samples:
    fig, ax = plt.subplots(1, 1)
    ax.boxplot([group1[p], group2[p], group3[p]])
    ax.set_xticklabels(["group1", "group2", "group3"])
    ax.set_ylabel("mean")
    plt.show()
    plt.imsave('/Users/.../Desktop/.../folder', ax)

But it does not save any plot to the folder, it just prints last plot and another one with all of the plots on it. I also tried using savefig() but also did not manage to save plots to my folder.

Additionally, it would be perfect if each plot had a name for example plot_p where p changes in a for loop, so I tried this:

plt.savefig("/Users/.../Desktop/.../folder/plot_{p}.png")

which gave me an error that more than 20 plots want to be opened (which is a good sign) but just 1 is saved in the folder.

2 Answers 2

1

I think you just need to change the order of plt.savefig() and plt.show() or just remove it. Try the following

for p in range(num):
    x = np.random.rand(num) #random code
    y = np.random.rand(num) #random code
    z = np.random.rand(num) #random code
    plt.boxplot([x,y,z]) #ploting
    plt.xticks([1,2,3],["group1", "group2", "group3"]) #plotting
    plt.savefig(f"/Users/.../Desktop/.../folder/name_you_wish_plot_to_have_{p}")
Sign up to request clarification or add additional context in comments.

7 Comments

And as name in plt.savefig(f"name_{p}") should I put the desired folder path or the name of the plot (but then how does it know that it has to be saved in this exact folder?) ?
f"/Users/.../Desktop/.../folder/name_you_wish_plot_to_have_{p}". I belive if the same name is used the plot will be overwritten.
I have just tried it and it just saves 1 plot in the folder (with the name I put and number, so the p worked) and prints also just 1 and another one again with every plot on one image.
could you post an image?
Added to the post. I tried adding plt.close() at the end of the code in the for loop, but the same result
|
0
for p in samples:
    fig, ax = plt.subplots(1, 1)
    ax.boxplot([group1[p], group2[p], group3[p]])
    ax.set_xticklabels(["group1", "group2", "group3"])
    ax.set_ylabel("mean")
    plt.savefig(f"/Users/.../Desktop/.../folder/name_{p}")
    plt.close()

This answer was posted as an edit to the question plots to folder python [SOLVED] by the OP barista under CC BY-SA 4.0.

Comments

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.