0

I've read When to use cla(), clf() or close() for clearing a plot in matplotlib? But still I couldn't find a nice solution to my problem.

I've a lot of data that needs to be plotted and saved to individual png or jpg file. Something like below but it really takes some memory and time to finish.

Is there anything that can be optimized? I'm thinking the background and the interface style, because I don't need the windows to display my figure, just save it would be enough.

Update: I tried to move plt.subplots() part outside the main loop. But then I can only get the full figure(axes,title and the plot line) for the first one. After the first pic, all pics have only axes and title but no data line.

Disclaimer: I'm saying that I don't need the picture to show. The script doesn't open up any window.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

def plot(tup):
    k, name, x, y = tup
    fig, ax = plt.subplots()
    ax.plot(x, y)


    for _x, _y in zip(x, y):
        ax.annotate(str(_y), (_x, _y + 0.2))

    fig.savefig('pics/{}.png'.format(k))
    fig.clf()

for e in alldata:
    plot(e)
dofine
  • 863
  • 1
  • 8
  • 20
  • Is this opening a window? For me it doesn't. – philippd Sep 04 '17 at 11:03
  • It shouldn't as it's not invoking the `show` command, and is fine since he wants to just save them directly. – Ignacio Vergara Kausel Sep 04 '17 at 11:07
  • You might use ipython, perhaps ipython within an IDE for scientific programming such as Spyder. Run your program in a normal terminal (i.e. > python xxx.py) and it won't open windows and significantly speed up the process. – hyamanieu Sep 04 '17 at 11:08
  • OP said he does not need the windows, but they should not be there anyways. – philippd Sep 04 '17 at 11:09
  • As you do now, you create the figure and everything else each time for each figure. The change I'd do to your code would be to put the main loop that calls your plot function inside the plot function itself and try to reuse the calls to the matplotlib library. – Ignacio Vergara Kausel Sep 04 '17 at 11:10
  • @philippd Hi, yes, it doesn't open up any window at all. My mistake in describing what I need. – dofine Sep 04 '17 at 11:17
  • Maybe try what @IgnacioVergaraKausel suggested. I think what he meant is to open one figure outside of the loop and then call fig.clear() instead of fig.clf() after saving. edit: Sorry, my mistake. I thought clf was short for closefig, but it is indeed short for clearfigure. So you only have to move the plt.subplots() out of the loop. – philippd Sep 04 '17 at 11:25

0 Answers0