##// END OF EJS Templates
figure.py and mpldriver.py: Schain error replaced by ValueError
Miguel Valdez -
r696:0851a4f75acb
parent child
Show More
@@ -1,625 +1,624
1 import os
1 import os
2 import numpy
2 import numpy
3 import time, datetime
3 import time, datetime
4 import mpldriver
4 import mpldriver
5
5
6 from schainpy.model.proc.jroproc_base import Operation
6 from schainpy.model.proc.jroproc_base import Operation
7
7
8 def isRealtime(utcdatatime):
8 def isRealtime(utcdatatime):
9
9 utcnow = time.mktime(time.localtime())
10 utcnow = time.mktime(time.localtime())
10 delta = abs(utcnow - utcdatatime) # abs
11 delta = abs(utcnow - utcdatatime) # abs
11 if delta >= 30.:
12 if delta >= 30.:
12 return False
13 return False
13 return True
14 return True
14
15
15 class Figure(Operation):
16 class Figure(Operation):
16
17
17 __driver = mpldriver
18 __driver = mpldriver
18 __isConfigThread = False
19 fig = None
19 fig = None
20
20
21 id = None
21 id = None
22 wintitle = None
22 wintitle = None
23 width = None
23 width = None
24 height = None
24 height = None
25 nplots = None
25 nplots = None
26 timerange = None
26 timerange = None
27
27
28 axesObjList = []
28 axesObjList = []
29
29
30 WIDTH = None
30 WIDTH = 300
31 HEIGHT = None
31 HEIGHT = 200
32 PREFIX = 'fig'
32 PREFIX = 'fig'
33
33
34 xmin = None
34 xmin = None
35 xmax = None
35 xmax = None
36
36
37 counter_imagwr = 0
37 counter_imagwr = 0
38
38
39 figfile = None
39 figfile = None
40
40
41 def __init__(self):
41 def __init__(self):
42
42
43 raise ValueError, "This method is not implemented"
43 raise NotImplementedError
44
44
45 def __del__(self):
45 def __del__(self):
46
46
47 self.__driver.closeFigure()
47 self.__driver.closeFigure()
48
48
49 def getFilename(self, name, ext='.png'):
49 def getFilename(self, name, ext='.png'):
50
50
51 path = '%s%03d' %(self.PREFIX, self.id)
51 path = '%s%03d' %(self.PREFIX, self.id)
52 filename = '%s_%s%s' %(self.PREFIX, name, ext)
52 filename = '%s_%s%s' %(self.PREFIX, name, ext)
53 return os.path.join(path, filename)
53 return os.path.join(path, filename)
54
54
55 def getAxesObjList(self):
55 def getAxesObjList(self):
56
56
57 return self.axesObjList
57 return self.axesObjList
58
58
59 def getSubplots(self):
59 def getSubplots(self):
60
60
61 raise ValueError, "Abstract method: This method should be defined"
61 raise NotImplementedError
62
62
63 def getScreenDim(self, widthplot, heightplot):
63 def getScreenDim(self, widthplot, heightplot):
64
64
65 nrow, ncol = self.getSubplots()
65 nrow, ncol = self.getSubplots()
66
66
67 widthscreen = widthplot*ncol
67 widthscreen = widthplot*ncol
68 heightscreen = heightplot*nrow
68 heightscreen = heightplot*nrow
69
69
70 return widthscreen, heightscreen
70 return widthscreen, heightscreen
71
71
72 def getTimeLim(self, x, xmin=None, xmax=None, timerange=None):
72 def getTimeLim(self, x, xmin=None, xmax=None, timerange=None):
73
73
74 if self.xmin != None and self.xmax != None:
74 if self.xmin != None and self.xmax != None:
75 if timerange == None:
75 if timerange == None:
76 timerange = self.xmax - self.xmin
76 timerange = self.xmax - self.xmin
77 xmin = self.xmin + timerange
77 xmin = self.xmin + timerange
78 xmax = self.xmax + timerange
78 xmax = self.xmax + timerange
79
79
80 return xmin, xmax
80 return xmin, xmax
81
81
82 if timerange == None and (xmin==None or xmax==None):
82 if timerange == None and (xmin==None or xmax==None):
83 timerange = 14400 #seconds
83 timerange = 14400 #seconds
84 #raise ValueError, "(timerange) or (xmin & xmax) should be defined"
85
84
86 if timerange != None:
85 if timerange != None:
87 txmin = x[0] #- x[0] % min(timerange/10, 10*60)
86 txmin = x[0] #- x[0] % min(timerange/10, 10*60)
88 else:
87 else:
89 txmin = x[0] #- x[0] % 10*60
88 txmin = x[0] #- x[0] % 10*60
90
89
91 thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
90 thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
92 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
91 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
93
92
94 if timerange != None:
93 if timerange != None:
95 xmin = (thisdatetime - thisdate).seconds/(60*60.)
94 xmin = (thisdatetime - thisdate).seconds/(60*60.)
96 xmax = xmin + timerange/(60*60.)
95 xmax = xmin + timerange/(60*60.)
97
96
98 mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
97 mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
99 xmin_sec = time.mktime(mindt.timetuple())
98 xmin_sec = time.mktime(mindt.timetuple())
100
99
101 maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
100 maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
102 xmax_sec = time.mktime(maxdt.timetuple())
101 xmax_sec = time.mktime(maxdt.timetuple())
103
102
104 return xmin_sec, xmax_sec
103 return xmin_sec, xmax_sec
105
104
106 def init(self, id, nplots, wintitle):
105 def init(self, id, nplots, wintitle):
107
106
108 raise ValueError, "This method has been replaced with createFigure"
107 raise NotImplementedError, "This method has been replaced with createFigure"
109
108
110 def createFigure(self, id, wintitle, widthplot=None, heightplot=None, show=True):
109 def createFigure(self, id, wintitle, widthplot=None, heightplot=None, show=True):
111
110
112 """
111 """
113 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
112 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
114 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
113 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
115 y self.HEIGHT y el numero de subplots (nrow, ncol)
114 y self.HEIGHT y el numero de subplots (nrow, ncol)
116
115
117 Input:
116 Input:
118 id : Los parametros necesarios son
117 id : Los parametros necesarios son
119 wintitle :
118 wintitle :
120
119
121 """
120 """
122
121
123 if widthplot == None:
122 if widthplot == None:
124 widthplot = self.WIDTH
123 widthplot = self.WIDTH
125
124
126 if heightplot == None:
125 if heightplot == None:
127 heightplot = self.HEIGHT
126 heightplot = self.HEIGHT
128
127
129 self.id = id
128 self.id = id
130
129
131 self.wintitle = wintitle
130 self.wintitle = wintitle
132
131
133 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
132 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
134
133
135 self.fig = self.__driver.createFigure(id=self.id,
134 self.fig = self.__driver.createFigure(id=self.id,
136 wintitle=self.wintitle,
135 wintitle=self.wintitle,
137 width=self.widthscreen,
136 width=self.widthscreen,
138 height=self.heightscreen,
137 height=self.heightscreen,
139 show=show)
138 show=show)
140
139
141 self.axesObjList = []
140 self.axesObjList = []
142 self.counter_imagwr = 0
141 self.counter_imagwr = 0
143
142
144
143
145 def setDriver(self, driver=mpldriver):
144 def setDriver(self, driver=mpldriver):
146
145
147 self.__driver = driver
146 self.__driver = driver
148
147
149 def setTitle(self, title):
148 def setTitle(self, title):
150
149
151 self.__driver.setTitle(self.fig, title)
150 self.__driver.setTitle(self.fig, title)
152
151
153 def setWinTitle(self, title):
152 def setWinTitle(self, title):
154
153
155 self.__driver.setWinTitle(self.fig, title=title)
154 self.__driver.setWinTitle(self.fig, title=title)
156
155
157 def setTextFromAxes(self, text):
156 def setTextFromAxes(self, text):
158
157
159 raise ValueError, "Este metodo ha sido reemplazaado con el metodo setText de la clase Axes"
158 raise NotImplementedError, "This method has been replaced with Axes.setText"
160
159
161 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
160 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
162
161
163 raise ValueError, "Este metodo ha sido reemplazaado con el metodo addAxes"
162 raise NotImplementedError, "This method has been replaced with Axes.addAxes"
164
163
165 def addAxes(self, *args):
164 def addAxes(self, *args):
166 """
165 """
167
166
168 Input:
167 Input:
169 *args : Los parametros necesarios son
168 *args : Los parametros necesarios son
170 nrow, ncol, xpos, ypos, colspan, rowspan
169 nrow, ncol, xpos, ypos, colspan, rowspan
171 """
170 """
172
171
173 axesObj = Axes(self.fig, *args)
172 axesObj = Axes(self.fig, *args)
174 self.axesObjList.append(axesObj)
173 self.axesObjList.append(axesObj)
175
174
176 def saveFigure(self, figpath, figfile, *args):
175 def saveFigure(self, figpath, figfile, *args):
177
176
178 filename = os.path.join(figpath, figfile)
177 filename = os.path.join(figpath, figfile)
179
178
180 fullpath = os.path.split(filename)[0]
179 fullpath = os.path.split(filename)[0]
181
180
182 if not os.path.exists(fullpath):
181 if not os.path.exists(fullpath):
183 subpath = os.path.split(fullpath)[0]
182 subpath = os.path.split(fullpath)[0]
184
183
185 if not os.path.exists(subpath):
184 if not os.path.exists(subpath):
186 os.mkdir(subpath)
185 os.mkdir(subpath)
187
186
188 os.mkdir(fullpath)
187 os.mkdir(fullpath)
189
188
190 self.__driver.saveFigure(self.fig, filename, *args)
189 self.__driver.saveFigure(self.fig, filename, *args)
191
190
192 def save(self, figpath, figfile=None, save=True, ftp=False, wr_period=1, thisDatetime=None, update_figfile=True):
191 def save(self, figpath, figfile=None, save=True, ftp=False, wr_period=1, thisDatetime=None, update_figfile=True):
193
192
194 self.counter_imagwr += 1
193 self.counter_imagwr += 1
195 if self.counter_imagwr < wr_period:
194 if self.counter_imagwr < wr_period:
196 return
195 return
197
196
198 self.counter_imagwr = 0
197 self.counter_imagwr = 0
199
198
200 if save:
199 if save:
201
200
202 if not figfile:
201 if not figfile:
203
202
204 if not thisDatetime:
203 if not thisDatetime:
205 raise ValueError, "Saving figure: figfile or thisDatetime should be defined"
204 raise ValueError, "Saving figure: figfile or thisDatetime should be defined"
206 return
205 return
207
206
208 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
207 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
209 figfile = self.getFilename(name = str_datetime)
208 figfile = self.getFilename(name = str_datetime)
210
209
211 if self.figfile == None:
210 if self.figfile == None:
212 self.figfile = figfile
211 self.figfile = figfile
213
212
214 if update_figfile:
213 if update_figfile:
215 self.figfile = figfile
214 self.figfile = figfile
216
215
217 # store png plot to local folder
216 # store png plot to local folder
218 self.saveFigure(figpath, self.figfile)
217 self.saveFigure(figpath, self.figfile)
219
218
220
219
221 if not ftp:
220 if not ftp:
222 return
221 return
223
222
224 if not thisDatetime:
223 if not thisDatetime:
225 return
224 return
226
225
227 # store png plot to FTP server according to RT-Web format
226 # store png plot to FTP server according to RT-Web format
228 ftp_filename = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
227 ftp_filename = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
229 # ftp_filename = os.path.join(figpath, name)
228 # ftp_filename = os.path.join(figpath, name)
230 self.saveFigure(figpath, ftp_filename)
229 self.saveFigure(figpath, ftp_filename)
231
230
232 def getNameToFtp(self, thisDatetime, FTP_WEI, EXP_CODE, SUB_EXP_CODE, PLOT_CODE, PLOT_POS):
231 def getNameToFtp(self, thisDatetime, FTP_WEI, EXP_CODE, SUB_EXP_CODE, PLOT_CODE, PLOT_POS):
233 YEAR_STR = '%4.4d'%thisDatetime.timetuple().tm_year
232 YEAR_STR = '%4.4d'%thisDatetime.timetuple().tm_year
234 DOY_STR = '%3.3d'%thisDatetime.timetuple().tm_yday
233 DOY_STR = '%3.3d'%thisDatetime.timetuple().tm_yday
235 FTP_WEI = '%2.2d'%FTP_WEI
234 FTP_WEI = '%2.2d'%FTP_WEI
236 EXP_CODE = '%3.3d'%EXP_CODE
235 EXP_CODE = '%3.3d'%EXP_CODE
237 SUB_EXP_CODE = '%2.2d'%SUB_EXP_CODE
236 SUB_EXP_CODE = '%2.2d'%SUB_EXP_CODE
238 PLOT_CODE = '%2.2d'%PLOT_CODE
237 PLOT_CODE = '%2.2d'%PLOT_CODE
239 PLOT_POS = '%2.2d'%PLOT_POS
238 PLOT_POS = '%2.2d'%PLOT_POS
240 name = YEAR_STR + DOY_STR + FTP_WEI + EXP_CODE + SUB_EXP_CODE + PLOT_CODE + PLOT_POS
239 name = YEAR_STR + DOY_STR + FTP_WEI + EXP_CODE + SUB_EXP_CODE + PLOT_CODE + PLOT_POS
241 return name
240 return name
242
241
243 def draw(self):
242 def draw(self):
244
243
245 self.__driver.draw(self.fig)
244 self.__driver.draw(self.fig)
246
245
247 def run(self):
246 def run(self):
248
247
249 raise ValueError, "This method is not implemented"
248 raise NotImplementedError
250
249
251 def close(self, show=False):
250 def close(self, show=False):
252
251
253 self.__driver.closeFigure(show=show, fig=self.fig)
252 self.__driver.closeFigure(show=show, fig=self.fig)
254
253
255 axesList = property(getAxesObjList)
254 axesList = property(getAxesObjList)
256
255
257
256
258 class Axes:
257 class Axes:
259
258
260 __driver = mpldriver
259 __driver = mpldriver
261 fig = None
260 fig = None
262 ax = None
261 ax = None
263 plot = None
262 plot = None
264 __missing = 1E30
263 __missing = 1E30
265 __firsttime = None
264 __firsttime = None
266
265
267 __showprofile = False
266 __showprofile = False
268
267
269 xmin = None
268 xmin = None
270 xmax = None
269 xmax = None
271 ymin = None
270 ymin = None
272 ymax = None
271 ymax = None
273 zmin = None
272 zmin = None
274 zmax = None
273 zmax = None
275
274
276 x_buffer = None
275 x_buffer = None
277 z_buffer = None
276 z_buffer = None
278
277
279 decimationx = None
278 decimationx = None
280 decimationy = None
279 decimationy = None
281
280
282 __MAXNUMX = 300
281 __MAXNUMX = 300
283 __MAXNUMY = 150
282 __MAXNUMY = 150
284
283
285 def __init__(self, *args):
284 def __init__(self, *args):
286
285
287 """
286 """
288
287
289 Input:
288 Input:
290 *args : Los parametros necesarios son
289 *args : Los parametros necesarios son
291 fig, nrow, ncol, xpos, ypos, colspan, rowspan
290 fig, nrow, ncol, xpos, ypos, colspan, rowspan
292 """
291 """
293
292
294 ax = self.__driver.createAxes(*args)
293 ax = self.__driver.createAxes(*args)
295 self.fig = args[0]
294 self.fig = args[0]
296 self.ax = ax
295 self.ax = ax
297 self.plot = None
296 self.plot = None
298
297
299 self.__firsttime = True
298 self.__firsttime = True
300 self.idlineList = []
299 self.idlineList = []
301
300
302 self.x_buffer = numpy.array([])
301 self.x_buffer = numpy.array([])
303 self.z_buffer = numpy.array([])
302 self.z_buffer = numpy.array([])
304
303
305 def setText(self, text):
304 def setText(self, text):
306
305
307 self.__driver.setAxesText(self.ax, text)
306 self.__driver.setAxesText(self.ax, text)
308
307
309 def setXAxisAsTime(self):
308 def setXAxisAsTime(self):
310 pass
309 pass
311
310
312 def pline(self, x, y,
311 def pline(self, x, y,
313 xmin=None, xmax=None,
312 xmin=None, xmax=None,
314 ymin=None, ymax=None,
313 ymin=None, ymax=None,
315 xlabel='', ylabel='',
314 xlabel='', ylabel='',
316 title='',
315 title='',
317 **kwargs):
316 **kwargs):
318
317
319 """
318 """
320
319
321 Input:
320 Input:
322 x :
321 x :
323 y :
322 y :
324 xmin :
323 xmin :
325 xmax :
324 xmax :
326 ymin :
325 ymin :
327 ymax :
326 ymax :
328 xlabel :
327 xlabel :
329 ylabel :
328 ylabel :
330 title :
329 title :
331 **kwargs : Los parametros aceptados son
330 **kwargs : Los parametros aceptados son
332
331
333 ticksize
332 ticksize
334 ytick_visible
333 ytick_visible
335 """
334 """
336
335
337 if self.__firsttime:
336 if self.__firsttime:
338
337
339 if xmin == None: xmin = numpy.nanmin(x)
338 if xmin == None: xmin = numpy.nanmin(x)
340 if xmax == None: xmax = numpy.nanmax(x)
339 if xmax == None: xmax = numpy.nanmax(x)
341 if ymin == None: ymin = numpy.nanmin(y)
340 if ymin == None: ymin = numpy.nanmin(y)
342 if ymax == None: ymax = numpy.nanmax(y)
341 if ymax == None: ymax = numpy.nanmax(y)
343
342
344 self.plot = self.__driver.createPline(self.ax, x, y,
343 self.plot = self.__driver.createPline(self.ax, x, y,
345 xmin, xmax,
344 xmin, xmax,
346 ymin, ymax,
345 ymin, ymax,
347 xlabel=xlabel,
346 xlabel=xlabel,
348 ylabel=ylabel,
347 ylabel=ylabel,
349 title=title,
348 title=title,
350 **kwargs)
349 **kwargs)
351
350
352 self.idlineList.append(0)
351 self.idlineList.append(0)
353 self.__firsttime = False
352 self.__firsttime = False
354 return
353 return
355
354
356 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
355 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
357 ylabel=ylabel,
356 ylabel=ylabel,
358 title=title)
357 title=title)
359
358
360 # self.__driver.pause()
359 # self.__driver.pause()
361
360
362 def addpline(self, x, y, idline, **kwargs):
361 def addpline(self, x, y, idline, **kwargs):
363 lines = self.ax.lines
362 lines = self.ax.lines
364
363
365 if idline in self.idlineList:
364 if idline in self.idlineList:
366 self.__driver.set_linedata(self.ax, x, y, idline)
365 self.__driver.set_linedata(self.ax, x, y, idline)
367
366
368 if idline not in(self.idlineList):
367 if idline not in(self.idlineList):
369 self.__driver.addpline(self.ax, x, y, **kwargs)
368 self.__driver.addpline(self.ax, x, y, **kwargs)
370 self.idlineList.append(idline)
369 self.idlineList.append(idline)
371
370
372 return
371 return
373
372
374 def pmultiline(self, x, y,
373 def pmultiline(self, x, y,
375 xmin=None, xmax=None,
374 xmin=None, xmax=None,
376 ymin=None, ymax=None,
375 ymin=None, ymax=None,
377 xlabel='', ylabel='',
376 xlabel='', ylabel='',
378 title='',
377 title='',
379 **kwargs):
378 **kwargs):
380
379
381 if self.__firsttime:
380 if self.__firsttime:
382
381
383 if xmin == None: xmin = numpy.nanmin(x)
382 if xmin == None: xmin = numpy.nanmin(x)
384 if xmax == None: xmax = numpy.nanmax(x)
383 if xmax == None: xmax = numpy.nanmax(x)
385 if ymin == None: ymin = numpy.nanmin(y)
384 if ymin == None: ymin = numpy.nanmin(y)
386 if ymax == None: ymax = numpy.nanmax(y)
385 if ymax == None: ymax = numpy.nanmax(y)
387
386
388 self.plot = self.__driver.createPmultiline(self.ax, x, y,
387 self.plot = self.__driver.createPmultiline(self.ax, x, y,
389 xmin, xmax,
388 xmin, xmax,
390 ymin, ymax,
389 ymin, ymax,
391 xlabel=xlabel,
390 xlabel=xlabel,
392 ylabel=ylabel,
391 ylabel=ylabel,
393 title=title,
392 title=title,
394 **kwargs)
393 **kwargs)
395 self.__firsttime = False
394 self.__firsttime = False
396 return
395 return
397
396
398 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
397 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
399 ylabel=ylabel,
398 ylabel=ylabel,
400 title=title)
399 title=title)
401
400
402 # self.__driver.pause()
401 # self.__driver.pause()
403
402
404 def pmultilineyaxis(self, x, y,
403 def pmultilineyaxis(self, x, y,
405 xmin=None, xmax=None,
404 xmin=None, xmax=None,
406 ymin=None, ymax=None,
405 ymin=None, ymax=None,
407 xlabel='', ylabel='',
406 xlabel='', ylabel='',
408 title='',
407 title='',
409 **kwargs):
408 **kwargs):
410
409
411 if self.__firsttime:
410 if self.__firsttime:
412
411
413 if xmin == None: xmin = numpy.nanmin(x)
412 if xmin == None: xmin = numpy.nanmin(x)
414 if xmax == None: xmax = numpy.nanmax(x)
413 if xmax == None: xmax = numpy.nanmax(x)
415 if ymin == None: ymin = numpy.nanmin(y)
414 if ymin == None: ymin = numpy.nanmin(y)
416 if ymax == None: ymax = numpy.nanmax(y)
415 if ymax == None: ymax = numpy.nanmax(y)
417
416
418 self.plot = self.__driver.createPmultilineYAxis(self.ax, x, y,
417 self.plot = self.__driver.createPmultilineYAxis(self.ax, x, y,
419 xmin, xmax,
418 xmin, xmax,
420 ymin, ymax,
419 ymin, ymax,
421 xlabel=xlabel,
420 xlabel=xlabel,
422 ylabel=ylabel,
421 ylabel=ylabel,
423 title=title,
422 title=title,
424 **kwargs)
423 **kwargs)
425 if self.xmin == None: self.xmin = xmin
424 if self.xmin == None: self.xmin = xmin
426 if self.xmax == None: self.xmax = xmax
425 if self.xmax == None: self.xmax = xmax
427 if self.ymin == None: self.ymin = ymin
426 if self.ymin == None: self.ymin = ymin
428 if self.ymax == None: self.ymax = ymax
427 if self.ymax == None: self.ymax = ymax
429
428
430 self.__firsttime = False
429 self.__firsttime = False
431 return
430 return
432
431
433 self.__driver.pmultilineyaxis(self.plot, x, y, xlabel=xlabel,
432 self.__driver.pmultilineyaxis(self.plot, x, y, xlabel=xlabel,
434 ylabel=ylabel,
433 ylabel=ylabel,
435 title=title)
434 title=title)
436
435
437 # self.__driver.pause()
436 # self.__driver.pause()
438
437
439 def pcolor(self, x, y, z,
438 def pcolor(self, x, y, z,
440 xmin=None, xmax=None,
439 xmin=None, xmax=None,
441 ymin=None, ymax=None,
440 ymin=None, ymax=None,
442 zmin=None, zmax=None,
441 zmin=None, zmax=None,
443 xlabel='', ylabel='',
442 xlabel='', ylabel='',
444 title='', rti = False, colormap='jet',
443 title='', rti = False, colormap='jet',
445 **kwargs):
444 **kwargs):
446
445
447 """
446 """
448 Input:
447 Input:
449 x :
448 x :
450 y :
449 y :
451 x :
450 x :
452 xmin :
451 xmin :
453 xmax :
452 xmax :
454 ymin :
453 ymin :
455 ymax :
454 ymax :
456 zmin :
455 zmin :
457 zmax :
456 zmax :
458 xlabel :
457 xlabel :
459 ylabel :
458 ylabel :
460 title :
459 title :
461 **kwargs : Los parametros aceptados son
460 **kwargs : Los parametros aceptados son
462 ticksize=9,
461 ticksize=9,
463 cblabel=''
462 cblabel=''
464 rti = True or False
463 rti = True or False
465 """
464 """
466
465
467 if self.__firsttime:
466 if self.__firsttime:
468
467
469 if xmin == None: xmin = numpy.nanmin(x)
468 if xmin == None: xmin = numpy.nanmin(x)
470 if xmax == None: xmax = numpy.nanmax(x)
469 if xmax == None: xmax = numpy.nanmax(x)
471 if ymin == None: ymin = numpy.nanmin(y)
470 if ymin == None: ymin = numpy.nanmin(y)
472 if ymax == None: ymax = numpy.nanmax(y)
471 if ymax == None: ymax = numpy.nanmax(y)
473 if zmin == None: zmin = numpy.nanmin(z)
472 if zmin == None: zmin = numpy.nanmin(z)
474 if zmax == None: zmax = numpy.nanmax(z)
473 if zmax == None: zmax = numpy.nanmax(z)
475
474
476
475
477 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
476 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
478 xmin, xmax,
477 xmin, xmax,
479 ymin, ymax,
478 ymin, ymax,
480 zmin, zmax,
479 zmin, zmax,
481 xlabel=xlabel,
480 xlabel=xlabel,
482 ylabel=ylabel,
481 ylabel=ylabel,
483 title=title,
482 title=title,
484 colormap=colormap,
483 colormap=colormap,
485 **kwargs)
484 **kwargs)
486
485
487 if self.xmin == None: self.xmin = xmin
486 if self.xmin == None: self.xmin = xmin
488 if self.xmax == None: self.xmax = xmax
487 if self.xmax == None: self.xmax = xmax
489 if self.ymin == None: self.ymin = ymin
488 if self.ymin == None: self.ymin = ymin
490 if self.ymax == None: self.ymax = ymax
489 if self.ymax == None: self.ymax = ymax
491 if self.zmin == None: self.zmin = zmin
490 if self.zmin == None: self.zmin = zmin
492 if self.zmax == None: self.zmax = zmax
491 if self.zmax == None: self.zmax = zmax
493
492
494 self.__firsttime = False
493 self.__firsttime = False
495 return
494 return
496
495
497 if rti:
496 if rti:
498 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
497 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
499 xlabel=xlabel,
498 xlabel=xlabel,
500 ylabel=ylabel,
499 ylabel=ylabel,
501 title=title,
500 title=title,
502 colormap=colormap)
501 colormap=colormap)
503 return
502 return
504
503
505 self.__driver.pcolor(self.plot, z,
504 self.__driver.pcolor(self.plot, z,
506 xlabel=xlabel,
505 xlabel=xlabel,
507 ylabel=ylabel,
506 ylabel=ylabel,
508 title=title)
507 title=title)
509
508
510 # self.__driver.pause()
509 # self.__driver.pause()
511
510
512 def pcolorbuffer(self, x, y, z,
511 def pcolorbuffer(self, x, y, z,
513 xmin=None, xmax=None,
512 xmin=None, xmax=None,
514 ymin=None, ymax=None,
513 ymin=None, ymax=None,
515 zmin=None, zmax=None,
514 zmin=None, zmax=None,
516 xlabel='', ylabel='',
515 xlabel='', ylabel='',
517 title='', rti = True, colormap='jet',
516 title='', rti = True, colormap='jet',
518 maxNumX = None, maxNumY = None,
517 maxNumX = None, maxNumY = None,
519 **kwargs):
518 **kwargs):
520
519
521 if maxNumX == None:
520 if maxNumX == None:
522 maxNumX = self.__MAXNUMX
521 maxNumX = self.__MAXNUMX
523
522
524 if maxNumY == None:
523 if maxNumY == None:
525 maxNumY = self.__MAXNUMY
524 maxNumY = self.__MAXNUMY
526
525
527 if self.__firsttime:
526 if self.__firsttime:
528 self.z_buffer = z
527 self.z_buffer = z
529 self.x_buffer = numpy.hstack((self.x_buffer, x))
528 self.x_buffer = numpy.hstack((self.x_buffer, x))
530
529
531 if xmin == None: xmin = numpy.nanmin(x)
530 if xmin == None: xmin = numpy.nanmin(x)
532 if xmax == None: xmax = numpy.nanmax(x)
531 if xmax == None: xmax = numpy.nanmax(x)
533 if ymin == None: ymin = numpy.nanmin(y)
532 if ymin == None: ymin = numpy.nanmin(y)
534 if ymax == None: ymax = numpy.nanmax(y)
533 if ymax == None: ymax = numpy.nanmax(y)
535 if zmin == None: zmin = numpy.nanmin(z)
534 if zmin == None: zmin = numpy.nanmin(z)
536 if zmax == None: zmax = numpy.nanmax(z)
535 if zmax == None: zmax = numpy.nanmax(z)
537
536
538
537
539 self.plot = self.__driver.createPcolor(self.ax, self.x_buffer, y, z,
538 self.plot = self.__driver.createPcolor(self.ax, self.x_buffer, y, z,
540 xmin, xmax,
539 xmin, xmax,
541 ymin, ymax,
540 ymin, ymax,
542 zmin, zmax,
541 zmin, zmax,
543 xlabel=xlabel,
542 xlabel=xlabel,
544 ylabel=ylabel,
543 ylabel=ylabel,
545 title=title,
544 title=title,
546 colormap=colormap,
545 colormap=colormap,
547 **kwargs)
546 **kwargs)
548
547
549 if self.xmin == None: self.xmin = xmin
548 if self.xmin == None: self.xmin = xmin
550 if self.xmax == None: self.xmax = xmax
549 if self.xmax == None: self.xmax = xmax
551 if self.ymin == None: self.ymin = ymin
550 if self.ymin == None: self.ymin = ymin
552 if self.ymax == None: self.ymax = ymax
551 if self.ymax == None: self.ymax = ymax
553 if self.zmin == None: self.zmin = zmin
552 if self.zmin == None: self.zmin = zmin
554 if self.zmax == None: self.zmax = zmax
553 if self.zmax == None: self.zmax = zmax
555
554
556 self.__firsttime = False
555 self.__firsttime = False
557 return
556 return
558
557
559 self.x_buffer = numpy.hstack((self.x_buffer, x[-1]))
558 self.x_buffer = numpy.hstack((self.x_buffer, x[-1]))
560 self.z_buffer = numpy.hstack((self.z_buffer, z))
559 self.z_buffer = numpy.hstack((self.z_buffer, z))
561
560
562 if self.decimationx == None:
561 if self.decimationx == None:
563 deltax = float(self.xmax - self.xmin)/maxNumX
562 deltax = float(self.xmax - self.xmin)/maxNumX
564 deltay = float(self.ymax - self.ymin)/maxNumY
563 deltay = float(self.ymax - self.ymin)/maxNumY
565
564
566 resolutionx = self.x_buffer[2]-self.x_buffer[0]
565 resolutionx = self.x_buffer[2]-self.x_buffer[0]
567 resolutiony = y[1]-y[0]
566 resolutiony = y[1]-y[0]
568
567
569 self.decimationx = numpy.ceil(deltax / resolutionx)
568 self.decimationx = numpy.ceil(deltax / resolutionx)
570 self.decimationy = numpy.ceil(deltay / resolutiony)
569 self.decimationy = numpy.ceil(deltay / resolutiony)
571
570
572 z_buffer = self.z_buffer.reshape(-1,len(y))
571 z_buffer = self.z_buffer.reshape(-1,len(y))
573
572
574 x_buffer = self.x_buffer[::self.decimationx]
573 x_buffer = self.x_buffer[::self.decimationx]
575 y_buffer = y[::self.decimationy]
574 y_buffer = y[::self.decimationy]
576 z_buffer = z_buffer[::self.decimationx, ::self.decimationy]
575 z_buffer = z_buffer[::self.decimationx, ::self.decimationy]
577 #===================================================
576 #===================================================
578
577
579 x_buffer, y_buffer, z_buffer = self.__fillGaps(x_buffer, y_buffer, z_buffer)
578 x_buffer, y_buffer, z_buffer = self.__fillGaps(x_buffer, y_buffer, z_buffer)
580
579
581 self.__driver.addpcolorbuffer(self.ax, x_buffer, y_buffer, z_buffer, self.zmin, self.zmax,
580 self.__driver.addpcolorbuffer(self.ax, x_buffer, y_buffer, z_buffer, self.zmin, self.zmax,
582 xlabel=xlabel,
581 xlabel=xlabel,
583 ylabel=ylabel,
582 ylabel=ylabel,
584 title=title,
583 title=title,
585 colormap=colormap)
584 colormap=colormap)
586
585
587 # self.__driver.pause()
586 # self.__driver.pause()
588
587
589 def polar(self, x, y,
588 def polar(self, x, y,
590 title='', xlabel='',ylabel='',**kwargs):
589 title='', xlabel='',ylabel='',**kwargs):
591
590
592 if self.__firsttime:
591 if self.__firsttime:
593 self.plot = self.__driver.createPolar(self.ax, x, y, title = title, xlabel = xlabel, ylabel = ylabel)
592 self.plot = self.__driver.createPolar(self.ax, x, y, title = title, xlabel = xlabel, ylabel = ylabel)
594 self.__firsttime = False
593 self.__firsttime = False
595 self.x_buffer = x
594 self.x_buffer = x
596 self.y_buffer = y
595 self.y_buffer = y
597 return
596 return
598
597
599 self.x_buffer = numpy.hstack((self.x_buffer,x))
598 self.x_buffer = numpy.hstack((self.x_buffer,x))
600 self.y_buffer = numpy.hstack((self.y_buffer,y))
599 self.y_buffer = numpy.hstack((self.y_buffer,y))
601 self.__driver.polar(self.plot, self.x_buffer, self.y_buffer, xlabel=xlabel,
600 self.__driver.polar(self.plot, self.x_buffer, self.y_buffer, xlabel=xlabel,
602 ylabel=ylabel,
601 ylabel=ylabel,
603 title=title)
602 title=title)
604
603
605 # self.__driver.pause()
604 # self.__driver.pause()
606
605
607 def __fillGaps(self, x_buffer, y_buffer, z_buffer):
606 def __fillGaps(self, x_buffer, y_buffer, z_buffer):
608
607
609 if x_buffer.shape[0] < 2:
608 if x_buffer.shape[0] < 2:
610 return x_buffer, y_buffer, z_buffer
609 return x_buffer, y_buffer, z_buffer
611
610
612 deltas = x_buffer[1:] - x_buffer[0:-1]
611 deltas = x_buffer[1:] - x_buffer[0:-1]
613 x_median = numpy.median(deltas)
612 x_median = numpy.median(deltas)
614
613
615 index = numpy.where(deltas > 5*x_median)
614 index = numpy.where(deltas > 5*x_median)
616
615
617 if len(index[0]) != 0:
616 if len(index[0]) != 0:
618 z_buffer[index[0],::] = self.__missing
617 z_buffer[index[0],::] = self.__missing
619 z_buffer = numpy.ma.masked_inside(z_buffer,0.99*self.__missing,1.01*self.__missing)
618 z_buffer = numpy.ma.masked_inside(z_buffer,0.99*self.__missing,1.01*self.__missing)
620
619
621 return x_buffer, y_buffer, z_buffer
620 return x_buffer, y_buffer, z_buffer
622
621
623
622
624
623
625 No newline at end of file
624
@@ -1,442 +1,442
1 import numpy
1 import numpy
2 import datetime
2 import datetime
3 import sys
3 import sys
4 import matplotlib
4 import matplotlib
5
5
6 if 'linux' in sys.platform:
6 if 'linux' in sys.platform:
7 matplotlib.use("TKAgg")
7 matplotlib.use("TKAgg")
8
8
9 if 'darwin' in sys.platform:
9 if 'darwin' in sys.platform:
10 matplotlib.use('WXAgg')
10 matplotlib.use('WXAgg')
11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
11 #Qt4Agg', 'GTK', 'GTKAgg', 'ps', 'agg', 'cairo', 'MacOSX', 'GTKCairo', 'WXAgg', 'template', 'TkAgg', 'GTK3Cairo', 'GTK3Agg', 'svg', 'WebAgg', 'CocoaAgg', 'emf', 'gdk', 'WX'
12 import matplotlib.pyplot
12 import matplotlib.pyplot
13
13
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
14 from mpl_toolkits.axes_grid1 import make_axes_locatable
15 from matplotlib.ticker import *
15 from matplotlib.ticker import FuncFormatter, LinearLocator
16
16
17 ###########################################
17 ###########################################
18 #Actualizacion de las funciones del driver
18 #Actualizacion de las funciones del driver
19 ###########################################
19 ###########################################
20
20
21 def createFigure(id, wintitle, width, height, facecolor="w", show=True):
21 def createFigure(id, wintitle, width, height, facecolor="w", show=True):
22
22
23 matplotlib.pyplot.ioff()
23 matplotlib.pyplot.ioff()
24 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor)
24 fig = matplotlib.pyplot.figure(num=id, facecolor=facecolor)
25 fig.canvas.manager.set_window_title(wintitle)
25 fig.canvas.manager.set_window_title(wintitle)
26 fig.canvas.manager.resize(width, height)
26 fig.canvas.manager.resize(width, height)
27 matplotlib.pyplot.ion()
27 matplotlib.pyplot.ion()
28 if show:
28 if show:
29 matplotlib.pyplot.show()
29 matplotlib.pyplot.show()
30
30
31 return fig
31 return fig
32
32
33 def closeFigure(show=False, fig=None):
33 def closeFigure(show=False, fig=None):
34
34
35 matplotlib.pyplot.ioff()
35 matplotlib.pyplot.ioff()
36 # matplotlib.pyplot.pause(0.1)
36 # matplotlib.pyplot.pause(0.1)
37
37
38 if show:
38 if show:
39 matplotlib.pyplot.show()
39 matplotlib.pyplot.show()
40
40
41 if fig != None:
41 if fig != None:
42 matplotlib.pyplot.close(fig.number)
42 matplotlib.pyplot.close(fig.number)
43 # matplotlib.pyplot.pause(0.1)
43 matplotlib.pyplot.pause(0.1)
44 # matplotlib.pyplot.ion()
44 # matplotlib.pyplot.ion()
45 return
45 return
46
46
47 matplotlib.pyplot.close("all")
47 matplotlib.pyplot.close("all")
48 # matplotlib.pyplot.pause(0.1)
48 matplotlib.pyplot.pause(0.1)
49 # matplotlib.pyplot.ion()
49 # matplotlib.pyplot.ion()
50 return
50 return
51
51
52 def saveFigure(fig, filename):
52 def saveFigure(fig, filename):
53
53
54 # matplotlib.pyplot.ioff()
54 # matplotlib.pyplot.ioff()
55 fig.savefig(filename)
55 fig.savefig(filename)
56 # matplotlib.pyplot.ion()
56 # matplotlib.pyplot.ion()
57
57
58 def setWinTitle(fig, title):
58 def setWinTitle(fig, title):
59
59
60 fig.canvas.manager.set_window_title(title)
60 fig.canvas.manager.set_window_title(title)
61
61
62 def setTitle(fig, title):
62 def setTitle(fig, title):
63
63
64 fig.suptitle(title)
64 fig.suptitle(title)
65
65
66 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
66 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan, polar=False):
67
67
68 matplotlib.pyplot.ioff()
68 matplotlib.pyplot.ioff()
69 matplotlib.pyplot.figure(fig.number)
69 matplotlib.pyplot.figure(fig.number)
70 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
70 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
71 (xpos, ypos),
71 (xpos, ypos),
72 colspan=colspan,
72 colspan=colspan,
73 rowspan=rowspan,
73 rowspan=rowspan,
74 polar=polar)
74 polar=polar)
75
75
76 matplotlib.pyplot.ion()
76 matplotlib.pyplot.ion()
77 return axes
77 return axes
78
78
79 def setAxesText(ax, text):
79 def setAxesText(ax, text):
80
80
81 ax.annotate(text,
81 ax.annotate(text,
82 xy = (.1, .99),
82 xy = (.1, .99),
83 xycoords = 'figure fraction',
83 xycoords = 'figure fraction',
84 horizontalalignment = 'left',
84 horizontalalignment = 'left',
85 verticalalignment = 'top',
85 verticalalignment = 'top',
86 fontsize = 10)
86 fontsize = 10)
87
87
88 def printLabels(ax, xlabel, ylabel, title):
88 def printLabels(ax, xlabel, ylabel, title):
89
89
90 ax.set_xlabel(xlabel, size=11)
90 ax.set_xlabel(xlabel, size=11)
91 ax.set_ylabel(ylabel, size=11)
91 ax.set_ylabel(ylabel, size=11)
92 ax.set_title(title, size=8)
92 ax.set_title(title, size=8)
93
93
94 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
94 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
95 ticksize=9, xtick_visible=True, ytick_visible=True,
95 ticksize=9, xtick_visible=True, ytick_visible=True,
96 nxticks=4, nyticks=10,
96 nxticks=4, nyticks=10,
97 grid=None,color='blue'):
97 grid=None,color='blue'):
98
98
99 """
99 """
100
100
101 Input:
101 Input:
102 grid : None, 'both', 'x', 'y'
102 grid : None, 'both', 'x', 'y'
103 """
103 """
104
104
105 matplotlib.pyplot.ioff()
105 matplotlib.pyplot.ioff()
106
106
107 ax.set_xlim([xmin,xmax])
107 ax.set_xlim([xmin,xmax])
108 ax.set_ylim([ymin,ymax])
108 ax.set_ylim([ymin,ymax])
109
109
110 printLabels(ax, xlabel, ylabel, title)
110 printLabels(ax, xlabel, ylabel, title)
111
111
112 ######################################################
112 ######################################################
113 if (xmax-xmin)<=1:
113 if (xmax-xmin)<=1:
114 xtickspos = numpy.linspace(xmin,xmax,nxticks)
114 xtickspos = numpy.linspace(xmin,xmax,nxticks)
115 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
115 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
116 ax.set_xticks(xtickspos)
116 ax.set_xticks(xtickspos)
117 else:
117 else:
118 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
118 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
119 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
119 # xtickspos = numpy.arange(nxticks)*float(xmax-xmin)/float(nxticks) + int(xmin)
120 ax.set_xticks(xtickspos)
120 ax.set_xticks(xtickspos)
121
121
122 for tick in ax.get_xticklabels():
122 for tick in ax.get_xticklabels():
123 tick.set_visible(xtick_visible)
123 tick.set_visible(xtick_visible)
124
124
125 for tick in ax.xaxis.get_major_ticks():
125 for tick in ax.xaxis.get_major_ticks():
126 tick.label.set_fontsize(ticksize)
126 tick.label.set_fontsize(ticksize)
127
127
128 ######################################################
128 ######################################################
129 for tick in ax.get_yticklabels():
129 for tick in ax.get_yticklabels():
130 tick.set_visible(ytick_visible)
130 tick.set_visible(ytick_visible)
131
131
132 for tick in ax.yaxis.get_major_ticks():
132 for tick in ax.yaxis.get_major_ticks():
133 tick.label.set_fontsize(ticksize)
133 tick.label.set_fontsize(ticksize)
134
134
135 ax.plot(x, y, color=color)
135 ax.plot(x, y, color=color)
136 iplot = ax.lines[-1]
136 iplot = ax.lines[-1]
137
137
138 ######################################################
138 ######################################################
139 if '0.' in matplotlib.__version__[0:2]:
139 if '0.' in matplotlib.__version__[0:2]:
140 print "The matplotlib version has to be updated to 1.1 or newer"
140 print "The matplotlib version has to be updated to 1.1 or newer"
141 return iplot
141 return iplot
142
142
143 if '1.0.' in matplotlib.__version__[0:4]:
143 if '1.0.' in matplotlib.__version__[0:4]:
144 print "The matplotlib version has to be updated to 1.1 or newer"
144 print "The matplotlib version has to be updated to 1.1 or newer"
145 return iplot
145 return iplot
146
146
147 if grid != None:
147 if grid != None:
148 ax.grid(b=True, which='major', axis=grid)
148 ax.grid(b=True, which='major', axis=grid)
149
149
150 matplotlib.pyplot.tight_layout()
150 matplotlib.pyplot.tight_layout()
151
151
152 matplotlib.pyplot.ion()
152 matplotlib.pyplot.ion()
153
153
154 return iplot
154 return iplot
155
155
156 def set_linedata(ax, x, y, idline):
156 def set_linedata(ax, x, y, idline):
157
157
158 ax.lines[idline].set_data(x,y)
158 ax.lines[idline].set_data(x,y)
159
159
160 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
160 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
161
161
162 ax = iplot.get_axes()
162 ax = iplot.get_axes()
163
163
164 printLabels(ax, xlabel, ylabel, title)
164 printLabels(ax, xlabel, ylabel, title)
165
165
166 set_linedata(ax, x, y, idline=0)
166 set_linedata(ax, x, y, idline=0)
167
167
168 def addpline(ax, x, y, color, linestyle, lw):
168 def addpline(ax, x, y, color, linestyle, lw):
169
169
170 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
170 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
171
171
172
172
173 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
173 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
174 xlabel='', ylabel='', title='', ticksize = 9,
174 xlabel='', ylabel='', title='', ticksize = 9,
175 colormap='jet',cblabel='', cbsize="5%",
175 colormap='jet',cblabel='', cbsize="5%",
176 XAxisAsTime=False):
176 XAxisAsTime=False):
177
177
178 matplotlib.pyplot.ioff()
178 matplotlib.pyplot.ioff()
179
179
180 divider = make_axes_locatable(ax)
180 divider = make_axes_locatable(ax)
181 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
181 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
182 fig = ax.get_figure()
182 fig = ax.get_figure()
183 fig.add_axes(ax_cb)
183 fig.add_axes(ax_cb)
184
184
185 ax.set_xlim([xmin,xmax])
185 ax.set_xlim([xmin,xmax])
186 ax.set_ylim([ymin,ymax])
186 ax.set_ylim([ymin,ymax])
187
187
188 printLabels(ax, xlabel, ylabel, title)
188 printLabels(ax, xlabel, ylabel, title)
189
189
190 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
190 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
191 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
191 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
192 cb.set_label(cblabel)
192 cb.set_label(cblabel)
193
193
194 # for tl in ax_cb.get_yticklabels():
194 # for tl in ax_cb.get_yticklabels():
195 # tl.set_visible(True)
195 # tl.set_visible(True)
196
196
197 for tick in ax.yaxis.get_major_ticks():
197 for tick in ax.yaxis.get_major_ticks():
198 tick.label.set_fontsize(ticksize)
198 tick.label.set_fontsize(ticksize)
199
199
200 for tick in ax.xaxis.get_major_ticks():
200 for tick in ax.xaxis.get_major_ticks():
201 tick.label.set_fontsize(ticksize)
201 tick.label.set_fontsize(ticksize)
202
202
203 for tick in cb.ax.get_yticklabels():
203 for tick in cb.ax.get_yticklabels():
204 tick.set_fontsize(ticksize)
204 tick.set_fontsize(ticksize)
205
205
206 ax_cb.yaxis.tick_right()
206 ax_cb.yaxis.tick_right()
207
207
208 if '0.' in matplotlib.__version__[0:2]:
208 if '0.' in matplotlib.__version__[0:2]:
209 print "The matplotlib version has to be updated to 1.1 or newer"
209 print "The matplotlib version has to be updated to 1.1 or newer"
210 return imesh
210 return imesh
211
211
212 if '1.0.' in matplotlib.__version__[0:4]:
212 if '1.0.' in matplotlib.__version__[0:4]:
213 print "The matplotlib version has to be updated to 1.1 or newer"
213 print "The matplotlib version has to be updated to 1.1 or newer"
214 return imesh
214 return imesh
215
215
216 matplotlib.pyplot.tight_layout()
216 matplotlib.pyplot.tight_layout()
217
217
218 if XAxisAsTime:
218 if XAxisAsTime:
219
219
220 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
220 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
221 ax.xaxis.set_major_formatter(FuncFormatter(func))
221 ax.xaxis.set_major_formatter(FuncFormatter(func))
222 ax.xaxis.set_major_locator(LinearLocator(7))
222 ax.xaxis.set_major_locator(LinearLocator(7))
223
223
224 matplotlib.pyplot.ion()
224 matplotlib.pyplot.ion()
225 return imesh
225 return imesh
226
226
227 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
227 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
228
228
229 z = z.T
229 z = z.T
230 ax = imesh.get_axes()
230 ax = imesh.get_axes()
231 printLabels(ax, xlabel, ylabel, title)
231 printLabels(ax, xlabel, ylabel, title)
232 imesh.set_array(z.ravel())
232 imesh.set_array(z.ravel())
233
233
234 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
234 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
235
235
236 printLabels(ax, xlabel, ylabel, title)
236 printLabels(ax, xlabel, ylabel, title)
237
237
238 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
238 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
239
239
240 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
240 def addpcolorbuffer(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
241
241
242 printLabels(ax, xlabel, ylabel, title)
242 printLabels(ax, xlabel, ylabel, title)
243
243
244 ax.collections.remove(ax.collections[0])
244 ax.collections.remove(ax.collections[0])
245
245
246 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
246 ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
247
247
248 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
248 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
249 ticksize=9, xtick_visible=True, ytick_visible=True,
249 ticksize=9, xtick_visible=True, ytick_visible=True,
250 nxticks=4, nyticks=10,
250 nxticks=4, nyticks=10,
251 grid=None):
251 grid=None):
252
252
253 """
253 """
254
254
255 Input:
255 Input:
256 grid : None, 'both', 'x', 'y'
256 grid : None, 'both', 'x', 'y'
257 """
257 """
258
258
259 matplotlib.pyplot.ioff()
259 matplotlib.pyplot.ioff()
260
260
261 lines = ax.plot(x.T, y)
261 lines = ax.plot(x.T, y)
262 leg = ax.legend(lines, legendlabels, loc='upper right')
262 leg = ax.legend(lines, legendlabels, loc='upper right')
263 leg.get_frame().set_alpha(0.5)
263 leg.get_frame().set_alpha(0.5)
264 ax.set_xlim([xmin,xmax])
264 ax.set_xlim([xmin,xmax])
265 ax.set_ylim([ymin,ymax])
265 ax.set_ylim([ymin,ymax])
266 printLabels(ax, xlabel, ylabel, title)
266 printLabels(ax, xlabel, ylabel, title)
267
267
268 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
268 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
269 ax.set_xticks(xtickspos)
269 ax.set_xticks(xtickspos)
270
270
271 for tick in ax.get_xticklabels():
271 for tick in ax.get_xticklabels():
272 tick.set_visible(xtick_visible)
272 tick.set_visible(xtick_visible)
273
273
274 for tick in ax.xaxis.get_major_ticks():
274 for tick in ax.xaxis.get_major_ticks():
275 tick.label.set_fontsize(ticksize)
275 tick.label.set_fontsize(ticksize)
276
276
277 for tick in ax.get_yticklabels():
277 for tick in ax.get_yticklabels():
278 tick.set_visible(ytick_visible)
278 tick.set_visible(ytick_visible)
279
279
280 for tick in ax.yaxis.get_major_ticks():
280 for tick in ax.yaxis.get_major_ticks():
281 tick.label.set_fontsize(ticksize)
281 tick.label.set_fontsize(ticksize)
282
282
283 iplot = ax.lines[-1]
283 iplot = ax.lines[-1]
284
284
285 if '0.' in matplotlib.__version__[0:2]:
285 if '0.' in matplotlib.__version__[0:2]:
286 print "The matplotlib version has to be updated to 1.1 or newer"
286 print "The matplotlib version has to be updated to 1.1 or newer"
287 return iplot
287 return iplot
288
288
289 if '1.0.' in matplotlib.__version__[0:4]:
289 if '1.0.' in matplotlib.__version__[0:4]:
290 print "The matplotlib version has to be updated to 1.1 or newer"
290 print "The matplotlib version has to be updated to 1.1 or newer"
291 return iplot
291 return iplot
292
292
293 if grid != None:
293 if grid != None:
294 ax.grid(b=True, which='major', axis=grid)
294 ax.grid(b=True, which='major', axis=grid)
295
295
296 matplotlib.pyplot.tight_layout()
296 matplotlib.pyplot.tight_layout()
297
297
298 matplotlib.pyplot.ion()
298 matplotlib.pyplot.ion()
299
299
300 return iplot
300 return iplot
301
301
302
302
303 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
303 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
304
304
305 ax = iplot.get_axes()
305 ax = iplot.get_axes()
306
306
307 printLabels(ax, xlabel, ylabel, title)
307 printLabels(ax, xlabel, ylabel, title)
308
308
309 for i in range(len(ax.lines)):
309 for i in range(len(ax.lines)):
310 line = ax.lines[i]
310 line = ax.lines[i]
311 line.set_data(x[i,:],y)
311 line.set_data(x[i,:],y)
312
312
313 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
313 def createPmultilineYAxis(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
314 ticksize=9, xtick_visible=True, ytick_visible=True,
314 ticksize=9, xtick_visible=True, ytick_visible=True,
315 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
315 nxticks=4, nyticks=10, marker='.', markersize=10, linestyle="None",
316 grid=None, XAxisAsTime=False):
316 grid=None, XAxisAsTime=False):
317
317
318 """
318 """
319
319
320 Input:
320 Input:
321 grid : None, 'both', 'x', 'y'
321 grid : None, 'both', 'x', 'y'
322 """
322 """
323
323
324 matplotlib.pyplot.ioff()
324 matplotlib.pyplot.ioff()
325
325
326 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
326 # lines = ax.plot(x, y.T, marker=marker,markersize=markersize,linestyle=linestyle)
327 lines = ax.plot(x, y.T, linestyle=linestyle, marker=marker, markersize=markersize)
327 lines = ax.plot(x, y.T, linestyle=linestyle, marker=marker, markersize=markersize)
328 leg = ax.legend(lines, legendlabels, loc='upper left', bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
328 leg = ax.legend(lines, legendlabels, loc='upper left', bbox_to_anchor=(1.01, 1.00), numpoints=1, handlelength=1.5, \
329 handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
329 handletextpad=0.5, borderpad=0.5, labelspacing=0.5, borderaxespad=0.)
330
330
331 for label in leg.get_texts(): label.set_fontsize(9)
331 for label in leg.get_texts(): label.set_fontsize(9)
332
332
333 ax.set_xlim([xmin,xmax])
333 ax.set_xlim([xmin,xmax])
334 ax.set_ylim([ymin,ymax])
334 ax.set_ylim([ymin,ymax])
335 printLabels(ax, xlabel, ylabel, title)
335 printLabels(ax, xlabel, ylabel, title)
336
336
337 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
337 # xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
338 # ax.set_xticks(xtickspos)
338 # ax.set_xticks(xtickspos)
339
339
340 for tick in ax.get_xticklabels():
340 for tick in ax.get_xticklabels():
341 tick.set_visible(xtick_visible)
341 tick.set_visible(xtick_visible)
342
342
343 for tick in ax.xaxis.get_major_ticks():
343 for tick in ax.xaxis.get_major_ticks():
344 tick.label.set_fontsize(ticksize)
344 tick.label.set_fontsize(ticksize)
345
345
346 for tick in ax.get_yticklabels():
346 for tick in ax.get_yticklabels():
347 tick.set_visible(ytick_visible)
347 tick.set_visible(ytick_visible)
348
348
349 for tick in ax.yaxis.get_major_ticks():
349 for tick in ax.yaxis.get_major_ticks():
350 tick.label.set_fontsize(ticksize)
350 tick.label.set_fontsize(ticksize)
351
351
352 iplot = ax.lines[-1]
352 iplot = ax.lines[-1]
353
353
354 if '0.' in matplotlib.__version__[0:2]:
354 if '0.' in matplotlib.__version__[0:2]:
355 print "The matplotlib version has to be updated to 1.1 or newer"
355 print "The matplotlib version has to be updated to 1.1 or newer"
356 return iplot
356 return iplot
357
357
358 if '1.0.' in matplotlib.__version__[0:4]:
358 if '1.0.' in matplotlib.__version__[0:4]:
359 print "The matplotlib version has to be updated to 1.1 or newer"
359 print "The matplotlib version has to be updated to 1.1 or newer"
360 return iplot
360 return iplot
361
361
362 if grid != None:
362 if grid != None:
363 ax.grid(b=True, which='major', axis=grid)
363 ax.grid(b=True, which='major', axis=grid)
364
364
365 matplotlib.pyplot.tight_layout()
365 matplotlib.pyplot.tight_layout()
366
366
367 if XAxisAsTime:
367 if XAxisAsTime:
368
368
369 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
369 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
370 ax.xaxis.set_major_formatter(FuncFormatter(func))
370 ax.xaxis.set_major_formatter(FuncFormatter(func))
371 ax.xaxis.set_major_locator(LinearLocator(7))
371 ax.xaxis.set_major_locator(LinearLocator(7))
372
372
373 matplotlib.pyplot.ion()
373 matplotlib.pyplot.ion()
374
374
375 return iplot
375 return iplot
376
376
377 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
377 def pmultilineyaxis(iplot, x, y, xlabel='', ylabel='', title=''):
378
378
379 ax = iplot.get_axes()
379 ax = iplot.get_axes()
380
380
381 printLabels(ax, xlabel, ylabel, title)
381 printLabels(ax, xlabel, ylabel, title)
382
382
383 for i in range(len(ax.lines)):
383 for i in range(len(ax.lines)):
384 line = ax.lines[i]
384 line = ax.lines[i]
385 line.set_data(x,y[i,:])
385 line.set_data(x,y[i,:])
386
386
387 def createPolar(ax, x, y,
387 def createPolar(ax, x, y,
388 xlabel='', ylabel='', title='', ticksize = 9,
388 xlabel='', ylabel='', title='', ticksize = 9,
389 colormap='jet',cblabel='', cbsize="5%",
389 colormap='jet',cblabel='', cbsize="5%",
390 XAxisAsTime=False):
390 XAxisAsTime=False):
391
391
392 matplotlib.pyplot.ioff()
392 matplotlib.pyplot.ioff()
393
393
394 ax.plot(x,y,'bo', markersize=5)
394 ax.plot(x,y,'bo', markersize=5)
395 # ax.set_rmax(90)
395 # ax.set_rmax(90)
396 ax.set_ylim(0,90)
396 ax.set_ylim(0,90)
397 ax.set_yticks(numpy.arange(0,90,20))
397 ax.set_yticks(numpy.arange(0,90,20))
398 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
398 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center' ,size='11')
399 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
399 # ax.text(0, 50, ylabel, rotation='vertical', va ='center', ha = 'left' ,size='11')
400 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
400 # ax.text(100, 100, 'example', ha='left', va='center', rotation='vertical')
401 ax.yaxis.labelpad = 230
401 ax.yaxis.labelpad = 230
402 printLabels(ax, xlabel, ylabel, title)
402 printLabels(ax, xlabel, ylabel, title)
403 iplot = ax.lines[-1]
403 iplot = ax.lines[-1]
404
404
405 if '0.' in matplotlib.__version__[0:2]:
405 if '0.' in matplotlib.__version__[0:2]:
406 print "The matplotlib version has to be updated to 1.1 or newer"
406 print "The matplotlib version has to be updated to 1.1 or newer"
407 return iplot
407 return iplot
408
408
409 if '1.0.' in matplotlib.__version__[0:4]:
409 if '1.0.' in matplotlib.__version__[0:4]:
410 print "The matplotlib version has to be updated to 1.1 or newer"
410 print "The matplotlib version has to be updated to 1.1 or newer"
411 return iplot
411 return iplot
412
412
413 # if grid != None:
413 # if grid != None:
414 # ax.grid(b=True, which='major', axis=grid)
414 # ax.grid(b=True, which='major', axis=grid)
415
415
416 matplotlib.pyplot.tight_layout()
416 matplotlib.pyplot.tight_layout()
417
417
418 matplotlib.pyplot.ion()
418 matplotlib.pyplot.ion()
419
419
420
420
421 return iplot
421 return iplot
422
422
423 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
423 def polar(iplot, x, y, xlabel='', ylabel='', title=''):
424
424
425 ax = iplot.get_axes()
425 ax = iplot.get_axes()
426
426
427 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
427 # ax.text(0, -110, ylabel, rotation='vertical', va ='center', ha = 'center',size='11')
428 printLabels(ax, xlabel, ylabel, title)
428 printLabels(ax, xlabel, ylabel, title)
429
429
430 set_linedata(ax, x, y, idline=0)
430 set_linedata(ax, x, y, idline=0)
431
431
432 def draw(fig):
432 def draw(fig):
433
433
434 if type(fig) == 'int':
434 if type(fig) == 'int':
435 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
435 raise ValueError, "Error drawing: Fig parameter should be a matplotlib figure object figure"
436
436
437 fig.canvas.draw()
437 fig.canvas.draw()
438
438
439 def pause(interval=0.000001):
439 def pause(interval=0.000001):
440
440
441 matplotlib.pyplot.pause(interval)
441 matplotlib.pyplot.pause(interval)
442 No newline at end of file
442
General Comments 0
You need to be logged in to leave comments. Login now