Python: Pyplot in loop & # 8594; curves accumulate during iteration, not separately

I would like to draw, for example. 10 lists, each list of which is represented by one curve and stored in a separate file, so nothing special.

The problem is that the constructed curves are not deleted after each iteration, so in each iteration / plot / file a new curve is simply added to the curves of previous iterations.

list1 = [...] ... list10 = [...] all_Lists = [list1, ..., list10] for i in range(10): pyplot.plot(all_Lists[i]) pyplot.savefig(...) 

file1 has 1 curve / list1.

file2 has 2 curves / list 1 + list2. ...

I would understand if someone could explain how to get one curve per plot using the for-loop. Thanks!

+4
source share
1 answer

I think the confusion is due to the fact that you are not using the OO interface. Pyplot is convenient, but handles a lot of things in the background, causing you to not know what is really happening. In your example, you create a shape and axis on the fly and continue to draw in the same axes.

Removing the axes before building the drawing will solve your problem, try adding pyplot.cla() as the first line of your loop.

I would rather make an object of a figure and axes:

 all_Lists = [list(np.random.randn(30).cumsum()) for i in range(10)] fig, ax = plt.subplots() for n, curv in enumerate(all_Lists): ax.cla() ax.plot(curv) fig.savefig() 
+2
source

Source: https://habr.com/ru/post/1500755/


All Articles