0

I have a Python code that contains a function where a figure is created in order to be saved as a pdf (it never shows on the screen during execution). For some reason, the execution of this subroutine keeps the figure open and blocks the following operations in the code. I tried to use the cla(), clf() and clear() functions but I could not get it to work...

Here is a partial view of the subroutine:

def trace_pdf(a,b,c,d):
   x = np.linspace(0,100,a)
   fig2 = plt.figure()
   ax2 = fig2.add_subplot(111)
   ax2.plot(b,c,'b', label='BA',linewidth=3.5)
   ax2.set_title('a pdf like no other')     
   fig2.savefig('file.pdf', format='pdf')       
   fig2.clf()
   fig2.clear()

I do not see why my code is blocked... (I checked that if I comment the call to the trace_pdf function, everything works fine).

Alain
  • 381
  • 3
  • 19
  • Are you sure that you don't have a `plt.show()` somewhere else in your code? – hitzg Feb 19 '15 at 19:59
  • Actually the code has a graphic interface that contains a few figures. So there is a `plt.show()` somewhere else in the code. – Alain Feb 19 '15 at 20:09
  • After checking all the source code, there is no plt.show() but canvas.show() that I replaced by canvas.draw(). Still, I can't find a way not to have my code blocked due to the subroutine. I am considering running this subroutine as a separate subprocess – Alain Feb 20 '15 at 13:39

1 Answers1

0

So here is what I did to fix my problem. I decided to try to run my function as an independent process so I added to my code:

from multiprocessing import Process, Queue

def trace_pdf(a,b,c,d):
   x = np.linspace(0,100,a)
   fig2 = plt.figure()
   ax2 = fig2.add_subplot(111)
   ax2.plot(b,c,'b', label='BA',linewidth=3.5)
   ax2.set_title('a pdf like no other')     
   fig2.savefig('file.pdf', format='pdf')       
   plt.close()

trace_pdf = Process(target=trace_pdf, args=(a,b,c,d))
trace_pdf.start()

This way, the plt_close() call does not impact the main graphic interface as I believe its action is limited to the separate process... For details regarding running a function as an independent process I used this post.

Community
  • 1
  • 1
Alain
  • 381
  • 3
  • 19