473,320 Members | 1,949 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Matplotlib show/draw works only once

I am writing a GUI program in Tkinter which allows the user to enter in different parameters specifying an ellipse segment. Then, he/she presses a button and the ellipse segment is plotted, using matplotlib. Here is the code (inside a class, but logically stands alone) that does this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. aa = DataArray(self.file0)  #Retrieve data sets
  3. bb = DataArray(self.file1)  #Not used right now
  4. cc = DataArray(self.file2)  #Not used right now
  5. curr = DataArray(self.file3)#Not used right now
  6.  
  7. x = aa.x                 #Get the abcissa values from the initial data set
  8.  
  9. ideal = IdealEllipse(float(self.r.get()) , float(self.r.get()), float(self.r.get()),xall)
  10.  
  11. plt1 = plt.plot(x,ideal)
  12.  
  13. plt.draw()
  14.  
  15.  

It works the first time, but if the user closes the window and then tries to plot it again, only a blank graph shows up. I have tried using pyplot.show(), and I get the same result. Even if I insert pyplot.close() at the top, to close all figures, it still does not change this. Using the figure manager and interactive mode also do not change this result. I have searched through the documentation and message boards all over the place but cannot find an explanation for this. I have the most up-to-date version of matplotlib (for Python 2.6). Why is this happening?

Thanks in advance for any help
Feb 17 '12 #1
3 3424
dwblas
626 Expert 512MB
What is self.r.get() and why do you call the function 3 times instead of calling it once and storing the value?
It works the first time, but if the user closes the window and then tries to plot it again, only a blank graph shows up
I'm guessing that r.get() doesn't exist once the window is closed but we can't tell from the code you posted. Storing r.get() in a variable would make the value persistent when the variable still exists after the window is closed.
Feb 17 '12 #2
This is all inside the command function for a button. I don't close the GUI, I just close the plot window. And then when I try to bring it back up by pressing the button, I get a blank graph. The repeated r.get() calls is a mistake. The whole function (as I am currently testing it) is:

Expand|Select|Wrap|Line Numbers
  1. def ParOpt(self):
  2.         Ready = (self.r.get() != '') and (self.rp.get() != '') and (self.th.get() != '')
  3.         Ready = Ready and (self.Chg1.get()!= '') and (self.Chg2.get()!= '')
  4.         Ready = Ready and (self.Name0.get() != '') and (self.Name1.get() != '')
  5.         Ready = Ready and (self.Name2.get() != '') and (self.Name3.get() != '')
  6.  
  7.         if Ready == 1:
  8.  
  9.             plt.ion()
  10.             aa = DataArray(self.file0)  #Retrieve data sets
  11.             bb = DataArray(self.file1)
  12.             cc = DataArray(self.file2)
  13.             curr = DataArray(self.file3)            
  14.  
  15.             d1 = float32(self.Chg1.get())
  16.             d2 = float32(self.Chg2.get())
  17.  
  18.             xall = aa.x                 #Get the abcissa values from the initial data set
  19.  
  20.             ideal = IdealEllipse(float(self.r.get()) , float(self.rp.get()), float(self.th.get()),xall)
  21.  
  22.             Solution = Optimize(ideal,aa.s,bb.s,cc.s,d1,d2,curr.s)
  23.  
  24.             s1 = str( SigFig(sqrt(Solution.disp[0,0]),sqrt(Solution.disp[0,0])) )
  25.             s2 = str( SigFig(sqrt(Solution.disp[1,1]),sqrt(Solution.disp[1,1])) )
  26.  
  27.             # See if answer is already open
  28.             try:
  29.                 answer
  30.             except NameError:
  31.                 answer = None
  32.  
  33.             # Test whether variable is defined to be None
  34.             if answer is not None:
  35.                 answer.destroy()
  36.  
  37.             answer = Toplevel()
  38.             answer.title("Optimal Parameter Settings")
  39.  
  40.             aL = Label(answer, text = "Change Bender #1 by "+str(SigFig(Solution.sol[0],float(s1)))+" (+/-"+s1+")",width = 50)
  41.             aL.pack()
  42.  
  43.             aL = Label(answer, text = "Change Bender #2 by "+str(SigFig(Solution.sol[1],float(s2)))+" (+/-"+s2+")",width = 50)
  44.             aL.pack()
  45.  
  46.             nd = [self.r.get()+'\t'+self.rp.get()+'\t'+self.th.get()+'\t'+str(d1)+'\t'+str(d2)+'\t'+'END\n']
  47.             nd.append(self.Name0.get()+'\t\n')
  48.             nd.append(self.Name1.get()+'\t\n')
  49.             nd.append(self.Name2.get()+'\t\n')
  50.             nd.append(self.Name3.get()+'\t\n')
  51.  
  52.             newDefaults = open('C:\Documents and Settings\dmerthe\Desktop\Merthe Ellipse Adjust Test Files\defaultvalues.txt','w')
  53.             newDefaults.writelines(nd)
  54.  
  55.             newDefaults.close()
  56.  
  57.             DiffInit = curr.s - ideal - mean(curr.s - ideal)
  58.             DiffFin = Solution.pred - ideal - mean(Solution.pred - ideal)
  59.  
  60.             cf1 = (bb.s - aa.s)/d1
  61.             cf2 = (cc.s - bb.s)/d2
  62.  
  63.             plt1 = plt.plot(xall,DiffInit,'b',xall,DiffFin,'r--')
  64.  
  65.             xRange = max(xall) - min(xall)
  66.             ymin1 = min(DiffInit)
  67.             ymax1 = max(DiffInit)
  68.             ymin2 = min(DiffFin)
  69.             ymax2 = max(DiffFin)
  70.             ymax = max([ymax1,ymax2])
  71.             yrange = max([ymax1,ymax2]) - min([ymin1,ymin2])
  72.  
  73.             sInit = SigFig(std(DiffInit),std(DiffInit)*1.0E-2)
  74.             sFin = SigFig(std(DiffFin),std(DiffFin)*1.0E-2)
  75.  
  76.             txt1 = plt.text(min(xall)+0.1*xRange, ymax, 'Current State, $\sigma = $'+str(sInit*1.0E6)+ ' $\mu$rad', color = 'blue', fontsize = 14)
  77.             txt2 = plt.text(min(xall)+0.1*xRange, ymax - 0.1*yrange, 'Predicted Final State, $\sigma = $'+str(sFin*1.0E6)+ ' $\mu$rad', color = 'red', fontsize = 14)
  78.  
  79.             plt.draw()
  80.             plt.ioff()
  81.  
Feb 17 '12 #3
dwblas
626 Expert 512MB
This code accepts a number and plots that number of ellipsis. When the plot window is closed it goes back to the Tkinter entry box to get another number, which you can then plot. Note that you can only do one thing at a time, so when the plot window is open the Tkinter window is not responsive.
Expand|Select|Wrap|Line Numbers
  1. try:
  2.     import Tkinter as tk     ## Python 2.x
  3. except ImportError:
  4.     import tkinter as tk     ## Python 3.x
  5.  
  6. from pylab import figure, show, rand
  7. from matplotlib.patches import Ellipse
  8.  
  9. class MatPlotTest():
  10.     def __init__(self):
  11.         self.num=1
  12.         self.root = tk.Tk()
  13.         self.create_entry()
  14.         self.root.mainloop()
  15.  
  16.     def create_entry(self):
  17.         tk.Label(self.root, text="number to create").grid()
  18.         self.entry=tk.Entry(self.root)
  19.         self.entry.grid(row=0, column=1)
  20.         self.entry.focus_set()
  21.  
  22.         tk.Button(self.root, text="draw ellipsesiess", command=self.plot_it, 
  23.                   bg="lightblue").grid(row=2, column=0)
  24.         tk.Button(self.root, text="Exit", command=self.root.quit, 
  25.                   bg="red").grid(row=2, column=1, sticky="WE")
  26.  
  27.     def plot_it(self):
  28.         self.num=int(self.entry.get())
  29.         ells = [Ellipse(xy=rand(2)*10, width=rand(), height=rand(), angle=rand()*360)
  30.                 for ctr in xrange(self.num)]
  31.  
  32.         fig = figure()
  33.         self.ax = fig.add_subplot(111, aspect='equal')
  34.         for e in ells:
  35.             self.ax.add_artist(e)
  36.             e.set_clip_box(self.ax.bbox)
  37.             e.set_alpha(rand())
  38.             e.set_facecolor(rand(3))
  39.  
  40.         self.ax.set_xlim(0, 10)
  41.         self.ax.set_ylim(0, 10)
  42.  
  43.         show()
  44.  
  45. MP=MatPlotTest() 
Feb 18 '12 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Vladimir Trebicky | last post by:
Hi, I've been trying to solve this problem for a long time. Only thing I did when upgrading from 3.25 to 4.0.14 I took the default my.cnf. I did not convert the privilege tables with...
2
by: rodger | last post by:
hi all, I have a form with two text boxes, a go button and a formula in the code to perform a calculation a value is entered in one text box, and press buttonm a result is computed which is...
4
by: Brandon | last post by:
I'm using an istringstream to convert some integers stored in string form to integers. However, each integer is stored in a differnt string. So, I used istringstream's str(string) method for the...
2
by: Isabel | last post by:
hi everyone, I have an annoying problem of with asp. Right now, when i type in data in textbox and hit submit, the text entered stays displayed in the textbox, however if I type in new data, it...
1
by: Kitchen Bin | last post by:
Hi. I am trying to use Sockets to do multiple Send and Receives via HTTP (not simultaneously). A first pair of Send/Receives works fine and sure enough I receive HTML back, but the next...
2
by: Jeff | last post by:
I am creating an ASP.NET 2.0 application that I want to embed a Windows Control into. Here are the steps: 1) I created a new Windows Control Library with a simple "hello world" app. 2) Compiled...
2
by: Frederic Rentsch | last post by:
Hi all, I have a class Time_Series derived from list. It lists days and contains a dictionary of various Lists also derived from list which contain values related to said days. (e.g. Stock...
4
by: jBunton | last post by:
I am using send object to generate emails BUT it works once then not again until I close and reopen my application. Thus in the code below only 1 email is generated - doesn't matter which of the...
2
by: dmitrey | last post by:
Hi all, here is a question already mentioned below, and I'm also interested in that one very much. unfortunatly, I can't write anything to matplotlib mailing lists because I constantly get server...
5
by: makthar | last post by:
Hi I have a JSP that calls an Ajax function when a button is clicked. The Ajax function calls a servlet . The Ajax function works well in Mozilla , but in IE7 when the button is clicked it works...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.