Package ComboCode :: Package cc :: Package plotting :: Module Plotting2
[hide private]
[frames] | no frames]

Source Code for Module ComboCode.cc.plotting.Plotting2

   1  # -*- coding: utf-8 -*- 
   2   
   3  """ 
   4  Preliminary plotting package in Pylab. 
   5   
   6  Author: R. Lombaert 
   7   
   8  """ 
   9   
  10  import pylab as pl 
  11  import os 
  12  import types 
  13  import numpy as np 
  14  from scipy import array, zeros 
  15  from scipy import argmax 
  16   
  17  from cc.tools.io import DataIO 
  18   
  19   
  20   
21 -def plotTiles(data,cfg='',**kwargs):
22 23 ''' 24 Plot data in tiles in a single figure. 25 26 The number of tiles in the x and y direction can be specified by the 27 dimensions keyword. 28 29 The data are then given in the form of a dictionary, in which each entry 30 describes the contents of a single tile. These dictionaries are passed in 31 a list of which the length is x-dim * y-dim. Can be less, but then no data 32 will be plotted in the final # tiles. 33 34 If length is less, and the keytags 35 keyword is included, the keytags will be put in the final tile. This only 36 works if all data dicts have the same amount of data lists. 37 38 The same line types are used for all tiles. They can be specified as well 39 as left to the default. 40 41 General properties can also be passed as extra keywords or as a cfg file, 42 as with the plotCols() method. 43 44 @param data: The data to be plotted. This list contains dictionaries that 45 include all information of a single tile in the plot. 46 47 Must be included in the dictionary: 48 49 x: list of lists giving the x-coords 50 51 y: list of lists giving the y-coords 52 53 Possible keywords in the dicts are: 54 55 xerr: List of arrays of x-errors. if [] no errors are included 56 on the plot. must have same len() as x, include None in the 57 list for data that have to be plotted without errors. 58 If upper and lower limits differ, instead of single array for 59 xerri, a list with two elements can be given as well with two 60 lists: one for the upper limit and one for the lower limit 61 62 yerr: List of arrays of y-errors. if [] no errors are included 63 on the plot. must have same len() as y, include None in the 64 list for data that have to be plotted without errors. 65 If upper and lower limits differ, instead of single array for 66 yerri, a list with two elements can be given as well with two 67 lists: one for the upper limit and one for the lower limit 68 69 labels: (labels, string, x-, y-position) 70 for label in a list, default [] 71 72 histoplot: list of indices of data lists to plot as histogram, 73 default [] 74 75 xmin, xmax, ymin and ymax: floats, default None 76 77 line_labels: (string,x-pos,same type-integer (eg molecule fi), 78 vibrational?) 79 for label indicating emission lines, default [] 80 81 xaxis: name of x axis (TeX enabled), if keyword not included 82 here, the method's xaxis is used. If not wanted, use empty 83 string 84 85 yaxis: name of y axis (TeX enabled), if keyword not included 86 here, the method's yaxis is used. If not wanted, use empty 87 string 88 89 @type data: list[dict] 90 @keyword dimensions: The number of tiles in the x and y direction is given: 91 (x-dim,y-dim) 92 93 (default: (1,len(data)) 94 @type dimensions: tuple(int) 95 @keyword cfg: config filename read as a dictionary, can replace any keyword 96 given to plotCols. Can also be a dictionary itself, in which 97 case no file is read and the kwargs are updated with the 98 content of cfg 99 100 (default: '') 101 @type cfg: string/dict 102 @keyword filename: filename of the figure, without extension and with path, 103 if None, the plot is just shown and not saved 104 105 (default: None) 106 @type filename: string 107 @keyword extension: extension of the plot filename, adds dot if not present 108 If None, three outputfiles are created: png, eps, pdf 109 Multiple extensions can be requested at the same time 110 through a list. 111 112 (default: pdf) 113 @type extension: string/list 114 @keyword figsize: the size of the figure, default is A4 page ratio 115 116 (default: (20.*np.sqrt(2.), 20.) ) 117 @type figsize: tuple(float,float) 118 @keyword show_plot: show fig before saving (hit enter to continue to save) 119 120 (default: 0) 121 @type show_plot: bool 122 @keyword xaxis: name of x axis (TeX enabled) 123 124 (default: r'$\lambda\ (\mu m)$') 125 @type xaxis: string 126 @keyword yaxis: name of y axis (TeX enabled) 127 128 (default: r'$F_\\nu (Jy)$') 129 @type yaxis: string 130 @keyword fontsize_key: fontsize of the keys 131 132 (default: 16) 133 @type fontsize_key: int 134 @keyword fontsize_axis: fontsize axis labels 135 136 (default: 24) 137 @type fontsize_axis: int 138 @keyword fontsize_title: fontsize title 139 140 (default: 26) 141 @type fontsize_title: int 142 @keyword fontsize_label: fontsize of the labels 143 144 (default: 12) 145 @type fontsize_label: int 146 @keyword fontsize_ticklabels: fontsize of axis tick labels 147 148 (default: 20) 149 @type fontsize_ticklabels: int 150 @keyword bold_ticklabels: boldface axis tick labels 151 152 (default: 0) 153 @type bold_ticklabels: bool 154 @keyword size_ticklines: The relative size of the tick lines 155 156 (default: 10) 157 @type size_ticklines: float 158 @keyword legend_numpoints: Number of points in the legend lines. 159 160 (default: 1) 161 @type legend_numpoints: int 162 @keyword keytags: if default no keys, else a key for every dataset in y in 163 all tiles. Is included in the final tile, so len of dicts 164 in data has to be x-dim * y-dim - 1 165 166 (default: []) 167 @type keytags: list[string] 168 @keyword line_label_types: line types for line labels if requested. 169 Overridden if number doesn't match number of 170 different labels requested. 171 172 (default: []) 173 @type line_label_types: list[string] 174 @keyword line_label_color: give different color to a linelabel based on 175 an integer. Black if off. If line_label_types 176 are given, this keyword is ignored. 177 178 (default: 0) 179 @type line_label_color: bool 180 @keyword line_label_lines: put vertical lines where linelabels occur 181 will be put at the x-position 182 183 (default: 0) 184 @type line_label_lines: bool 185 @keyword baseline_line_labels: linelabels at the baseline instead of at 186 the bottom 187 188 (default: 0) 189 @type baseline_line_labels: bool 190 @keyword no_line_label_text: Don't show text for line labels, only lines are 191 shown if requested. 192 193 (default: 0) 194 @type no_line_label_text: bool 195 @keyword short_label_lines: The label lines are short and at the top of plot 196 197 (default:0) 198 @type short_label_lines: bool 199 @keyword line_label_spectrum: linelabels are set at the top and bottom of 200 the spectrum, as for PACS spectra. If 2, all 201 labels are set at the top. 202 203 (default: 0) 204 @type line_label_spectrum: bool 205 @keyword line_label_linewidth: The line width of line label lines. 206 207 (default: 2) 208 @type line_label_linewidth: int 209 @keyword line_label_dashedvib: Use dashed lines for vibrational transitions 210 in line label lines. Only applied if the 211 ground state label line is a full line. 212 213 (default: 0) 214 @type line_label_dashedvib: bool 215 @keyword linewidth: width of all the lines in the plot 216 217 (default: 1) 218 @type linewidth: int 219 @keyword thick_lw_data: Use twice the linewidth for data points (through 220 histoplot keyword). 221 222 (default: 0) 223 @type thick_lw_data: bool 224 @keyword xlogscale: set logarithmic scale of x-axis 225 226 (default: 0) 227 @type xlogscale: bool 228 @keyword ylogscale: set logarithmic scale of y-axis 229 230 (default: 0) 231 @type ylogscale: bool 232 @keyword xmin: if default then autoscaling is done, otherwise min x value. 233 Only used when ddict entries are not defined. 234 235 (default: None) 236 @type xmin: float 237 @keyword xmax: if default then autoscaling is done, otherwise max x value 238 Only used when ddict entries are not defined. 239 240 (default: None) 241 @type xmax: float 242 @keyword ymin: if default then autoscaling is done, otherwise min y value 243 Only used when ddict entries are not defined. 244 245 (default: None) 246 @type ymin: float 247 @keyword ymax: if default then autoscaling is done, otherwise max y value 248 Only used when ddict entries are not defined. 249 250 (default: None) 251 @type ymax: float 252 @keyword transparent: for a transparent background 253 254 (default: 0) 255 @type transparent: bool 256 @keyword removeYvalues: remove all Y tickmarks on the Y axis 257 258 (default: 0) 259 @type removeYvalues: bool 260 @keyword removeXvalues: remove all X tickmarks on the X axis 261 262 (default: 0) 263 @type removeXvalues: bool 264 @keyword line_types: if empty, standard line types are used 265 if an entry is 0, standard line types are used 266 line types are pythonesque ('-k', line style + color) 267 if list is not empty, take len equal to len(x) 268 269 (default: []) 270 271 Colors: 272 - r: red 273 - y: yellow 274 - b: blue 275 - c: cyan 276 - g: green 277 - k: black 278 - m: magenta 279 - [0 and 1]: grayscale 280 (always as a 3-digit float, e.g. 0.75!!) 281 282 283 Styles: 284 - -: line 285 - s: squares 286 - o: large filled circles 287 - .: small filled circles 288 - --: stripes 289 - -.: stripe-point line 290 - x: crosses 291 - +: pluses 292 - p: pentagons 293 - d: filled circle + vertical line 294 - |: vertical line 295 - h,H: different hexagons 296 - *: stars 297 - 2,3,4: "triple crosses" in different orientations 298 - v,>,<,^: Triangles in different orientations 299 @type line_types: list[string] 300 @keyword wspace: Adjust the width between subplots horizontally 301 302 (default: 0.2) 303 @type wspace: float 304 @keyword hspace: Adjust the width between subplots vertically 305 306 (default: 0.2) 307 @type hspace: float 308 @keyword ws_bot: Adjust the amount of white space at the bottom 309 310 (default: 0.1) 311 @type ws_bot: float 312 @keyword ws_top: Adjust the amount of white space at the top 313 314 (default: 0.9) 315 @type ws_top: float 316 @keyword ws_left: Adjust the amount of white space at the left 317 318 (default: 0.125) 319 @type ws_left: float 320 @keyword ws_right: Adjust the amount of white space at the bottom 321 322 (default: 0.9) 323 @type ws_right: float 324 @keyword landscape: Save the plot in landscape orientation 325 326 (default: 0) 327 @type landscape: bool 328 @keyword markeredgewidth: Increase the linewidth of marker edges (eg black 329 circles around colored points) or the thickness 330 of crosses, dots, etc... Also used for the size 331 of error bar caps. 332 333 (default: 1) 334 @type markeredgewidth: int 335 336 @return: the plotfilename with extension is returned 337 @rtype: string 338 339 ''' 340 341 if cfg: 342 if type(cfg) is types.DictType: 343 kwargs.update(cfg) 344 else: 345 kwargs.update(readCfg(cfg)) 346 filename=kwargs.get('filename',None) 347 extension=kwargs.get('extension','pdf') 348 figsize=kwargs.get('figsize',(20.*np.sqrt(2.), 20.)) 349 show_plot=kwargs.get('show_plot',0) 350 xaxis=kwargs.get('xaxis',r'$\lambda$ ($\mu$m)') 351 yaxis=kwargs.get('yaxis',r'$F_\nu$ (Jy)') 352 fontsize_key=kwargs.get('fontsize_key',20) 353 fontsize_axis=kwargs.get('fontsize_axis',24) 354 fontsize_title=kwargs.get('fontsize_title',26) 355 fontsize_label=kwargs.get('fontsize_label',12) 356 fontsize_ticklabels=kwargs.get('fontsize_ticklabels',20) 357 bold_ticklabels=kwargs.get('bold_ticklabels',0) 358 linewidth=kwargs.get('linewidth',1) 359 xlogscale=kwargs.get('xlogscale',0) 360 ylogscale=kwargs.get('ylogscale',0) 361 transparent=kwargs.get('transparent',0) 362 removeYvalues=kwargs.get('removeYvalues',0) 363 removeXvalues=kwargs.get('removeXvalues',0) 364 keytags=kwargs.get('keytags',[]) 365 legend_numpoints=kwargs.get('legend_numpoints',1) 366 line_types=kwargs.get('line_types',[]) 367 xmin=kwargs.get('xmin',None) 368 xmax=kwargs.get('xmax',None) 369 ymin=kwargs.get('ymin',None) 370 ymax=kwargs.get('ymax',None) 371 wspace = kwargs.get('wspace',0.2) 372 hspace = kwargs.get('hspace',0.2) 373 ws_bot = kwargs.get('ws_bot',0.1) 374 ws_top = kwargs.get('ws_top',0.9) 375 ws_left = kwargs.get('ws_left',0.125) 376 ws_right = kwargs.get('ws_right',0.9) 377 baseline_line_labels=kwargs.get('baseline_line_labels',0) 378 line_label_types=kwargs.get('line_label_types',[]) 379 line_label_color=kwargs.get('line_label_color',0) 380 line_label_lines=kwargs.get('line_label_lines',0) 381 line_label_spectrum=kwargs.get('line_label_spectrum',0) 382 line_label_dashedvib=kwargs.get('line_label_dashedvib',0) 383 no_line_label_text=kwargs.get('no_line_label_text',0) 384 line_label_linewidth=kwargs.get('line_label_linewidth',2) 385 size_ticklines=kwargs.get('size_ticklines',10) 386 landscape = kwargs.get('landscape',0) 387 short_label_lines = kwargs.get('short_label_lines',0) 388 thick_lw_data = kwargs.get('thick_lw_data',0) 389 markeredgewidth = kwargs.get('markeredgewidth',1) 390 391 #-- Set default dimensions to be one column, and #rows == #curves 392 nd = len(data) 393 dimensions=kwargs.get('dimensions',(1,nd+1 if keytags else nd)) 394 395 xdim = int(dimensions[0]) 396 ydim = int(dimensions[1]) 397 if keytags: 398 if not len(data) <= (xdim*ydim)-1: 399 print 'Too many dicts in data to be accomodated by requested ' + \ 400 'dimensions, including keytags on the last tile. Aborting.' 401 return 402 else: 403 xlens = array([len(ddict['x']) for ddict in data]) 404 imaxlen = argmax(xlens) 405 maxlen = max(xlens) 406 if not len(keytags) == maxlen: 407 print 'Number of keytags does not equal number of datasets. '+\ 408 'Leaving them out.' 409 keytags = [] 410 else: 411 #- copy the data list such that it does not mess with the original 412 data = list(data) 413 data.append(dict([('x',[[0]]*maxlen),('y',[[0]]*maxlen)])) 414 else: 415 if not len(data) <= xdim*ydim: 416 print 'Too many dicts in data to be accomodated by requested ' + \ 417 'dimensions. Aborting.' 418 return 419 for i,ddict in enumerate(data): 420 if not ddict.has_key('x') or not ddict.has_key('y'): 421 print 'Dictionary in data list with index %i does not '%i + \ 422 'have either the x or the y keyword. Aborting.' 423 return 424 if len(ddict['x']) != len(ddict['y']): 425 print 'Dictionary in data list with index %i does not '%i + \ 426 'the same dimensions for the x and y lists. Aborting.' 427 return 428 if not ddict.has_key('histoplot'): 429 ddict['histoplot'] = [] 430 if not ddict.has_key('labels'): 431 ddict['labels'] = [] 432 if not ddict.has_key('xmin'): 433 ddict['xmin'] = xmin 434 if not ddict.has_key('xmax'): 435 ddict['xmax'] = xmax 436 if not ddict.has_key('ymin'): 437 ddict['ymin'] = ymin 438 if not ddict.has_key('ymax'): 439 ddict['ymax'] = ymax 440 if not ddict.has_key('line_labels'): 441 ddict['line_labels'] = [] 442 if not ddict.has_key('xaxis'): 443 ddict['xaxis'] = xaxis 444 if not ddict.has_key('yaxis'): 445 ddict['yaxis'] = yaxis 446 if not ddict.has_key('yerr'): 447 ddict['yerr'] = [None]*len(ddict['x']) 448 if not ddict.has_key('xerr'): 449 ddict['xerr'] = [None]*len(ddict['x']) 450 451 pl.rc('text', usetex=True) 452 pl.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) 453 # Figure properties 454 figprops = dict(figsize=figsize) 455 # New figure 456 fig = pl.figure(**figprops) 457 fig.subplots_adjust(wspace=wspace) 458 fig.subplots_adjust(hspace=hspace) 459 fig.subplots_adjust(bottom=ws_bot) 460 fig.subplots_adjust(top=ws_top) 461 fig.subplots_adjust(right=ws_right) 462 fig.subplots_adjust(left=ws_left) 463 464 if transparent: 465 fig.patch.set_alpha(0.5) 466 if not line_types: 467 line_types = getLineTypes() 468 for ddict,itile in zip(data,xrange(xdim*ydim)): 469 sub = pl.subplot(ydim,xdim,itile+1) 470 these_data = [] 471 [these_data.append([xi,yi,lp,xerri,yerri]) 472 for xi,yi,lp,xerri,yerri in zip(ddict['x'],ddict['y'],line_types,\ 473 ddict['xerr'],ddict['yerr']) 474 if list(yi) and not yi is None] 475 for index,(xi,yi,lp,xerri,yerri) in enumerate(these_data): 476 ls,col = splitLineType(lp) 477 if index in ddict['histoplot']: 478 leg = sub.step(xi,yi,ls,where='mid',color=col,\ 479 linewidth=(thick_lw_data and linewidth*2 or linewidth)) 480 else: 481 leg = sub.plot(xi,yi,ls,linewidth= linewidth,color=col) 482 if '--' in lp: 483 leg[0].set_dashes([15,5]) 484 if '.-' in lp or '-.' in lp: 485 leg[0].set_dashes([15,5,2,5]) 486 if not xerri is None: 487 try: 488 test = len(xerri[0]) 489 lls = xerri[0] 490 if len(xerri) == 1: 491 uls = xerri[0] 492 else: 493 uls = xerri[1] 494 except TypeError: 495 lls = xerri 496 uls = xerri 497 for (ll,ul,xii,yii) in zip(lls,uls,xi,yi): 498 if ll != 0 or ul != 0: 499 sub.errorbar(x=[xii],y=[yii],xerr=[[ll],[ul]],\ 500 ecolor=col,\ 501 lolims=ll==0,\ 502 uplims=ul==0,\ 503 fmt="none",\ 504 capsize=5,\ 505 markeredgewidth=markeredgewidth,\ 506 elinewidth=linewidth/2.,\ 507 barsabove=True)#,zorder=zo,alpha=alph) 508 if not yerri is None: 509 try: 510 test = len(yerri[0]) 511 lls = yerri[0] 512 if len(yerri) == 1: 513 uls = yerri[0] 514 else: 515 uls = yerri[1] 516 except TypeError: 517 lls = yerri 518 uls = yerri 519 for (ll,ul,xii,yii) in zip(lls,uls,xi,yi): 520 if ll != 0 or ul != 0: 521 sub.errorbar(x=[xii],y=[yii],yerr=[[ll],[ul]],\ 522 ecolor=col,\ 523 lolims=ll==0,\ 524 uplims=ul==0,\ 525 fmt="none",\ 526 capsize=5,\ 527 markeredgewidth=markeredgewidth,\ 528 elinewidth=linewidth/2.,\ 529 barsabove=False)#,zorder=zo,alpha=alph) 530 531 532 533 if keytags and itile == len(data)-1: 534 prop = pl.matplotlib.font_manager.FontProperties(size=fontsize_key) 535 lg = pl.legend(tuple(keytags),loc=(0,0),prop=prop,\ 536 numpoints=legend_numpoints) 537 lg.legendPatch.set_alpha(0.0) 538 ax = pl.gca() 539 ax.get_xaxis().set_visible(False) 540 ax.get_yaxis().set_visible(False) 541 pl.xlim(xmax=-1) 542 else: 543 sub.autoscale_view(tight=True,scaley=False) 544 if xlogscale: 545 sub.set_xscale('log') 546 if ylogscale: 547 sub.set_yscale('log') 548 pl.ylabel(ddict['yaxis'],fontsize=fontsize_axis) 549 pl.xlabel(ddict['xaxis'],fontsize=fontsize_axis) 550 ax = pl.gca() 551 if ddict['labels']: 552 for s,x,y in ddict['labels']: 553 pl.text(x,y,s,transform=ax.transAxes,fontsize=fontsize_label) 554 if ddict['line_labels']: 555 y_pos = max([max(yi) for yi in ddict['y'] if yi.size])*1.3 556 xmin = min([min(xi) for xi in ddict['x'] if xi.size]) 557 xmax = max([max(xi) for xi in ddict['x'] if xi.size]) 558 setLineLabels(line_labels=ddict['line_labels'],y_pos=y_pos,\ 559 line_label_spectrum=line_label_spectrum,\ 560 line_label_color=line_label_color,\ 561 line_label_lines=line_label_lines,\ 562 baseline_line_labels=baseline_line_labels,\ 563 fontsize_label=fontsize_label,\ 564 no_line_label_text=no_line_label_text,\ 565 short_label_lines=short_label_lines,\ 566 line_label_types=line_label_types,\ 567 linewidth=line_label_linewidth,xmin=xmin,\ 568 xmax=xmax,\ 569 line_label_dashedvib=line_label_dashedvib) 570 if removeYvalues: 571 ax.set_yticks([]) 572 if removeXvalues: 573 ax.set_xticks([]) 574 for label in ax.xaxis.get_ticklabels() + ax.yaxis.get_ticklabels(): 575 label.set_fontsize(fontsize_ticklabels) 576 if bold_ticklabels: 577 label.set_fontweight('bold') 578 for tl in sub.get_xticklines() + sub.get_yticklines(): 579 tl.set_markersize(size_ticklines) 580 tl.set_markeredgewidth(1.2) 581 for tl in sub.yaxis.get_minorticklines() + sub.xaxis.get_minorticklines(): 582 tl.set_markersize(size_ticklines/2.) 583 tl.set_markeredgewidth(1.2) 584 pl.axes(ax) 585 if transparent: 586 ax.patch.set_alpha(0.6) 587 if not ddict['xmin'] is None: 588 pl.xlim(xmin=ddict['xmin']) # min([min(xi) for xi in x]) 589 if not ddict['xmax'] is None: 590 pl.xlim(xmax=ddict['xmax']) 591 if not ddict['ymin'] is None: 592 pl.ylim(ymin=ddict['ymin']) # min([min(xi) for xi in x]) 593 if not ddict['ymax'] is None: 594 pl.ylim(ymax=ddict['ymax']) 595 if filename: filename = saveFig(filename,extension,landscape) 596 if show_plot or filename is None: 597 pl.subplots_adjust(bottom=0.45) 598 pl.subplots_adjust(top=0.95) 599 pl.subplots_adjust(right=0.7) 600 pl.subplots_adjust(left=0.05) 601 pl.show() 602 pl.close('all') 603 604 return filename
605 606 607
608 -def plotCols(x=[],y=[],xerr=[],yerr=[],cfg='',**kwargs):
609 610 ''' 611 Plot a spectrum, with or without a number of subplots. 612 613 Pylab can be made to show the plot before saving, and will do so anyway if 614 the filename is not defined, in which case no file will be saved. 615 616 The Pylab figure types can be used here, by setting the extension keyword. 617 618 @keyword x: List of lists/arrays of x-values, requires inputfilenames if [] 619 620 (default: []) 621 @type x: list[list/arrays/...] 622 @keyword y: List of lists/arrays of y-values, requires inputfilenames if [] 623 624 (default: []) 625 @type y: list[list/arrays/...] 626 @keyword xerr: lists with syntax: xerr[xerri] or xerr[[xerri_low,xerri_up]] 627 if [] no errors are included on the plot 628 Must have same len() as x, include None in the list for data 629 that have to be plotted without errors, while other data do 630 have errors associated with them. 631 If upper and lower limits differ, instead of single 632 array/list for xerri, a list with two elements can be given 633 as well with two lists: one for the upper limit and one for 634 the lower limit 635 For now errorbar color is same as data color 636 637 (default: []) 638 @type xerr: list[list/arrays/...] 639 @keyword yerr: List of lists/arrays of y-errs 640 if [] no errors are included on the plot 641 Must have same len() as y, include None in the list for data 642 that have to be plotted without errors, while other data do 643 have errors associated with them. 644 For now errorbar color is same as data color 645 If upper and lower limits differ, instead of single 646 array/list for yerri, a list with two elements can be given 647 as well with two lists: one for the upper limit and one for 648 the lower limit 649 650 (default: []) 651 @type yerr: list[list/arrays/...] 652 @keyword twiny_x: If a second list of datasets has to be plotted with a 653 different yaxis, include the second x axis data here. 654 Only works for two different y axes, with a single x axis. 655 656 (default: []) 657 @type twiny_x: list[array] 658 @keyword twiny_y: If a second list of datasets has to be plotted with a 659 different yaxis, include the second y axis data here. 660 Only works for two different y axes, with a single x axis. 661 662 (default: []) 663 @type twiny_y: list[array] 664 @keyword inputfiles: list of filenames with two up to six input columns 665 (x|y) or (x|y|xerr) or (x|y|xerr|yerr) or 666 (x|y|xerr_low|xerr_up|yerr_low|yerr_up) 667 If no yerr, three columns will do. If yerr, xerr must 668 be included as well. Use 0's if there is no error on x. 669 If upper and lower limits differ, then include 6 670 columns in total. Cols 3 and 4 are xerr_low and 671 xerr_up respectively. Cols 5 and 6 are yerr_low and 672 yerr_up respectively. All 6 must be included in this 673 case! No combinations possible. 674 675 (default: []) 676 @type inputfiles: list[string] 677 @keyword cfg: config filename read as a dictionary, can replace any keyword 678 given to plotCols. Can also be a dictionary itself, in which 679 case no file is read and the kwargs are updated with the 680 content of cfg 681 682 (default: '') 683 @type cfg: string/dict 684 @keyword filename: filename of the figure, without extension and with path, 685 if None, the plot is just shown and not saved 686 687 (default: None) 688 @type filename: string 689 @keyword extension: extension of the plot filename, adds dot if not present 690 If None, three output files are created: png, eps, pdf 691 Multiple extensions can be requested at the same time 692 through a list. 693 694 (default: pdf) 695 @type extension: string/list 696 @keyword number_subplots: #subplots in which to plot in vertical direction 697 698 (default: 1) 699 @type number_subplots: int 700 @keyword figsize: the size of the figure, A4 page ratio is 701 (20.*np.sqrt(2.), 20.). Default is other ratio. 702 703 (default: (12.5,8) ) 704 @type figsize: tuple(float,float) 705 @keyword show_plot: show fig before saving (hit enter to continue to save) 706 707 (default: 0) 708 @type show_plot: bool 709 @keyword xaxis: name of x axis (TeX enabled) 710 711 (default: r'$\lambda\ (\mu m)$') 712 @type xaxis: string 713 @keyword all_xaxislabels: Include xaxis labels for every subplot, in case 714 number_subplots != 1. If off, only the bottom 715 subplot gets an xaxis label. 716 717 (default: 0) 718 @type all_xaxislabels: bool 719 @keyword yaxis: name of y axis (TeX enabled) 720 721 (default: r'$F_\\nu (Jy)$') 722 @type yaxis: string 723 @keyword twinyaxis: name of twin y axis (TeX enabled) if twinx and twiny 724 are not empty. If this is None then the twiny_x and 725 twin_y are ignored. Also ignored if number_subplots!=1 726 727 (default: None) 728 @type twinyaxis: string 729 @keyword plot_title: plot title (TeX enabled), if empty string no title is 730 used 731 732 (default: '') 733 @type plot_title: string 734 @keyword fontsize_key: fontsize of the keys 735 736 (default: 20) 737 @type fontsize_key: int 738 @keyword fontsize_axis: fontsize axis labels 739 740 (default: 26) 741 @type fontsize_axis: int 742 @keyword fontsize_title: fontsize title 743 744 (default: 26) 745 @type fontsize_title: int 746 @keyword fontsize_label: fontsize of the labels 747 748 (default: 18) 749 @type fontsize_label: int 750 @keyword fontsize_localized_label: fontsize of the localized labels 751 752 (default: 18) 753 @type fontsize_localized_label: int 754 @keyword fontsize_ticklabels: fontsize of axis tick labels 755 756 (default: 26) 757 @type fontsize_ticklabels: int 758 @keyword bold_ticklabels: boldface axis tick labels 759 760 (default: 0) 761 @type bold_ticklabels: bool 762 @keyword legend_numpoints: Number of points in the legend lines. 763 764 (default: 1) 765 @type legend_numpoints: int 766 @keyword keytags: if default no keys, else a key for every dataset in y 767 768 (default: []) 769 @type keytags: list[string] 770 @keyword twiny_keytags: as keytags, but only if not twinyaxis is None. 771 772 (default: []) 773 @type twiny_keytags: list[string] 774 @keyword size_ticklines: The relative size of the tick lines 775 776 (default: 10) 777 @type size_ticklines: float 778 @keyword labels: string, x-, y-position for label, positions in fig coords: 779 0.0 bottom left, 1,1 upper right 780 781 (default: []) 782 @type labels: list[(string,float,float)] 783 @keyword localized_labels: Same as labels, but with the xpos given in 784 axis coordinates instead of figure coordinates. 785 Useful for labels you only want to appear in 786 multi-subplot figures in certain subplots. In 787 addition the color of the text is given as an 788 extra entry. 789 790 (default: []) 791 @type localized_labels: list[(string,float,float,string)] 792 @keyword line_labels: (string,x-pos and same type-integer (eg molecule fi), 793 vibrational?) 794 for the label,specifically to indicate emission lines 795 796 (default: []) 797 @type line_labels: list[(string,float,int)] 798 @keyword line_label_types: line types for line labels if requested. 799 Overridden if number doesn't match number of 800 different labels requested. 801 802 (default: []) 803 @type line_label_types: list[string] 804 @keyword line_label_color: give different color to a linelabel based on 805 an integer. Black if off. If line_label_types 806 are given, this keyword is ignored. 807 808 (default: 0) 809 @type line_label_color: bool 810 @keyword line_label_lines: put vertical lines where linelabels occur 811 will be put at the x-position 812 813 (default: 0) 814 @type line_label_lines: bool 815 @keyword baseline_line_labels: linelabels at the baseline instead of at 816 the bottom 817 818 (default: 0) 819 @type baseline_line_labels: bool 820 @keyword line_label_spectrum: linelabels are set at the top and bottom of 821 the spectrum, as for PACS spectra. If 2, all 822 labels are set at the top. 823 824 (default: 0) 825 @type line_label_spectrum: bool 826 @keyword no_line_label_text: Don't show text for line labels, only lines are 827 shown if requested. 828 829 (default: 0) 830 @type no_line_label_text: bool 831 @keyword short_label_lines: The label lines are short and at the top of plot 832 833 (default:0) 834 @type short_label_lines: bool 835 @keyword line_label_linewidth: The line width of line label lines. 836 837 (default: 2) 838 @type line_label_linewidth: int 839 @keyword line_label_dashedvib: Use dashed lines for vibrational transitions 840 in line label lines. Only applied if the 841 ground state label line is a full line. 842 843 (default: 0) 844 @type line_label_dashedvib: bool 845 @keyword markeredgewidth: Increase the linewidth of marker edges (eg black 846 circles around colored points) or the thickness 847 of crosses, dots, etc... 848 849 (default: 1) 850 @type markeredgewidth: int 851 @keyword xerr_markeredgewidth: The linewidth of the caps of x error bars. 852 853 (default: 1) 854 @type xerr_markeredgewidth: int 855 @keyword yerr_markeredgewidth: The linewidth of the caps of y error bars. 856 857 (default: 1) 858 @type yerr_markeredgewidth: int 859 @keyword xerr_capsize: The size or length of the caps on the x error bars. 860 861 (default: 5) 862 @type xerr_capsize: int 863 @keyword yerr_capsize: The size or length of the caps on the y error bars. 864 865 (default: 5) 866 @type yerr_capsize: int 867 868 @keyword thick_lw_data: Use twice the linewidth for data points (through 869 histoplot keyword). 870 871 (default: 0) 872 @type thick_lw_data: bool 873 @keyword linewidth: width of the non-symbol line types 874 875 (default: 3) 876 @type linewidth: int 877 @keyword xerr_linewidth: width of the x error bars 878 879 (default: linewidth/2.) 880 @type xerr_linewidth: int 881 @keyword yerr_linewidth: width of the y error bars 882 883 (default: linewidth/2.) 884 @type yerr_linewidth: int 885 @keyword key_location: location of the key in the plot in figure coords. 886 Can be 'best' as well to allow python to figure out 887 the best location 888 889 (default: 'best' ) 890 @type key_location: tuple/str 891 @keyword xlogscale: set logarithmic scale of x-axis 892 893 (default: 0) 894 @type xlogscale: bool 895 @keyword ylogscale: set logarithmic scale of y-axis 896 897 (default: 0) 898 @type ylogscale: bool 899 @keyword twiny_logscale: set logarithmic scale of the twiny-axis 900 901 (default: 0) 902 @type twiny_logscale: bool 903 @keyword xmin: if default then autoscaling is done, otherwise min x value 904 905 (default: None) 906 @type xmin: float 907 @keyword xmax: if default then autoscaling is done, otherwise max x value 908 909 (default: None) 910 @type xmax: float 911 @keyword ymin: if default then autoscaling is done, otherwise min y value 912 913 (default: None) 914 @type ymin: float 915 @keyword ymax: if default then autoscaling is done, otherwise max y value 916 917 (default: None) 918 @type ymax: float 919 @keyword twiny_ymin: if default then autoscaling is done, otherwise min y 920 value for the twiny axis 921 922 (default: None) 923 @type twiny_ymin: float 924 @keyword twiny_ymax: if default then autoscaling is done, otherwise min y 925 value for the twiny axis 926 927 (default: None) 928 @type twiny_ymax: float 929 @keyword transparent: for a transparent background 930 931 (default: 0) 932 @type transparent: bool 933 @keyword removeYvalues: remove all Y tickmarks on the Y axis 934 935 (default: 0) 936 @type removeYvalues: bool 937 @keyword removeXvalues: remove all X tickmarks on the X axis 938 939 (default: 0) 940 @type removeXvalues: bool 941 @keyword histoplot: plot as histogram for data indices given in this list 942 respective to their positions in the x and y inputlists 943 944 (default: []) 945 @type histoplot: list 946 @keyword line_types: if empty, standard line types are used 947 if an entry is 0, standard line types are used 948 line types are pythonesque ('-k', line style + color) 949 if list is not empty, take len equal to len(x) 950 951 (default: []) 952 953 Colors: 954 - r: red 955 - y: yellow 956 - b: blue 957 - c: cyan 958 - g: green 959 - k: black 960 - m: magenta 961 - [0 and 1]: grayscale 962 (always as a 3-digit float, e.g. 0.75!!) 963 964 Styles: 965 - -: line 966 - s: squares 967 - o: large filled circles 968 - .: small filled circles 969 - --: stripes 970 - -.: stripe-point line 971 - x: crosses 972 - +: pluses 973 - p: pentagons 974 - d: filled circle + vertical line 975 - |: vertical line 976 - h,H: different hexagons 977 - *: stars 978 - 2,3,4: "triple crosses" in different orientations 979 - v,>,<,^: Triangles in different orientations 980 @type line_types: list[string] 981 @keyword markersize: Give different markersize for each x-plot here. If a 982 single number, the markersize is used for all datasets 983 Default values are set to 5. 984 985 (default: []) 986 @type markersize: list 987 @keyword zorder: List that matches the x and y grids. Number gives the 988 index of the layer that is requested for the respective 989 datasets. Higher number means the datasets will be on top 990 of lower numbered datasets. Default goes for no preferred 991 ordering. 992 993 (default: []) 994 @type zorder: list 995 @keyword alpha: List that matches the x and y grids. Values give the 996 opacity of the plotted curve. 997 998 (default: []) 999 @type alpha: list 1000 @keyword twiny_line_types: As line_types, but for the twiny data. 1001 1002 (default: []) 1003 @type twiny_line_types: list[string] 1004 @keyword horiz_lines: a list of y-coords to put full black horizontal lines 1005 1006 (default: []) 1007 @type horiz_lines: list[float] 1008 @keyword horiz_rect: a list of tuples to set a horizontal colored 1009 transparent rectangle on the plot. tuple(y1,y2,color) 1010 1011 (default: []) 1012 @type horiz_rect: list[tuple] 1013 @keyword vert_lines: a list of x-coords to put full black vertical lines 1014 1015 (default: []) 1016 @type vert_lines: list[float] 1017 @keyword vert_rect: a list of tuples to set a vertical colored transparent 1018 rectangle on the plot. tuple(x1,x2,color) 1019 1020 (default: []) 1021 @type vert_rect: list[tuple] 1022 @keyword ws_bot: Adjust the amount of white space at the bottom 1023 1024 (default: 0.1) 1025 @type ws_bot: float 1026 @keyword ws_top: Adjust the amount of white space at the top 1027 1028 (default: 0.9) 1029 @type ws_top: float 1030 @keyword ws_left: Adjust the amount of white space at the left 1031 1032 (default: 0.125) 1033 @type ws_left: float 1034 @keyword ws_right: Adjust the amount of white space at the bottom 1035 1036 (default: 0.9) 1037 @type ws_right: float 1038 @keyword hspace: Adjust the width between subplots vertically 1039 1040 (default: 0.2) 1041 @type hspace: float 1042 @keyword landscape: Save the plot in landscape orientation 1043 1044 (default: 0) 1045 @type landscape: bool 1046 @keyword arrows: Draw arrows in a plot. (x0,y0,delta(x),delta(y),width,col,zorder) 1047 works like localized_labels. 1048 1049 (default: []) 1050 @type arrows: list[list] 1051 1052 @return: the plotfilename with extension is returned 1053 @rtype: string 1054 1055 ''' 1056 1057 if cfg: 1058 if type(cfg) is types.DictType: 1059 kwargs.update(cfg) 1060 else: 1061 kwargs.update(readCfg(cfg)) 1062 inputfiles=kwargs.get('inputfiles',[]) 1063 filename=kwargs.get('filename',None) 1064 extension=kwargs.get('extension','pdf') 1065 number_subplots=int(kwargs.get('number_subplots',1)) 1066 figsize=kwargs.get('figsize',(12.5,8.)) 1067 show_plot=kwargs.get('show_plot',0) 1068 twiny_x = kwargs.get('twiny_x',[]) 1069 twiny_y = kwargs.get('twiny_y',[]) 1070 xaxis=kwargs.get('xaxis',r'$\lambda$\ ($\mu m$)') 1071 yaxis=kwargs.get('yaxis',r'$F_\nu$ ($Jy$)') 1072 twinyaxis=kwargs.get('twinyaxis',None) 1073 plot_title=kwargs.get('plot_title','') 1074 fontsize_key=kwargs.get('fontsize_key',20) 1075 fontsize_axis=kwargs.get('fontsize_axis',26) 1076 fontsize_title=kwargs.get('fontsize_title',26) 1077 fontsize_label=kwargs.get('fontsize_label',18) 1078 fontsize_localized_label=kwargs.get('fontsize_localized_label',18) 1079 fontsize_ticklabels=kwargs.get('fontsize_ticklabels',20) 1080 bold_ticklabels=kwargs.get('bold_ticklabels',0) 1081 size_ticklines=kwargs.get('size_ticklines',10) 1082 keytags=kwargs.get('keytags',[]) 1083 legend_numpoints=kwargs.get('legend_numpoints',1) 1084 twiny_keytags=kwargs.get('twiny_keytags',[]) 1085 labels=kwargs.get('labels',[]) 1086 localized_labels=kwargs.get('localized_labels',[]) 1087 linewidth=kwargs.get('linewidth',3) 1088 xerr_linewidth=kwargs.get('xerr_linewidth',linewidth/2.) 1089 yerr_linewidth=kwargs.get('yerr_linewidth',linewidth/2.) 1090 markeredgewidth=kwargs.get('markeredgewidth',1) 1091 xerr_markeredgewidth=kwargs.get('xerr_markeredgewidth',1) 1092 yerr_markeredgewidth=kwargs.get('yerr_markeredgewidth',1) 1093 xerr_capsize=kwargs.get('xerr_capsize',5) 1094 yerr_capsize=kwargs.get('yerr_capsize',5) 1095 key_location=kwargs.get('key_location','best') 1096 xlogscale=kwargs.get('xlogscale',0) 1097 ylogscale=kwargs.get('ylogscale',0) 1098 twiny_logscale=kwargs.get('twiny_logscale',0) 1099 xmin=kwargs.get('xmin',None) 1100 xmax=kwargs.get('xmax',None) 1101 ymin=kwargs.get('ymin',None) 1102 ymax=kwargs.get('ymax',None) 1103 twiny_ymin=kwargs.get('twiny_ymin',None) 1104 twiny_ymax=kwargs.get('twiny_ymax',None) 1105 transparent=kwargs.get('transparent',0) 1106 removeYvalues=kwargs.get('removeYvalues',0) 1107 removeXvalues=kwargs.get('removeXvalues',0) 1108 histoplot=kwargs.get('histoplot',[]) 1109 line_types=kwargs.get('line_types',[]) 1110 twiny_line_types=kwargs.get('twiny_line_types',[]) 1111 baseline_line_labels=kwargs.get('baseline_line_labels',0) 1112 line_labels=kwargs.get('line_labels',[]) 1113 line_label_types=kwargs.get('line_label_types',[]) 1114 line_label_color=kwargs.get('line_label_color',0) 1115 line_label_lines=kwargs.get('line_label_lines',0) 1116 line_label_spectrum=kwargs.get('line_label_spectrum',0) 1117 line_label_linewidth=kwargs.get('line_label_linewidth',2) 1118 line_label_dashedvib=kwargs.get('line_label_dashedvib',0) 1119 no_line_label_text=kwargs.get('no_line_label_text',0) 1120 horiz_lines=kwargs.get('horiz_lines',[]) 1121 vert_lines=kwargs.get('vert_lines',[]) 1122 horiz_rect=kwargs.get('horiz_rect',[]) 1123 vert_rect=kwargs.get('vert_rect',[]) 1124 ws_bot = kwargs.get('ws_bot',0.1) 1125 ws_top = kwargs.get('ws_top',0.9) 1126 ws_left = kwargs.get('ws_left',0.125) 1127 ws_right = kwargs.get('ws_right',0.9) 1128 hspace = kwargs.get('hspace',0.2) 1129 landscape = kwargs.get('landscape',0) 1130 thick_lw_data = kwargs.get('thick_lw_data',0) 1131 short_label_lines = kwargs.get('short_label_lines',0) 1132 all_xaxislabels = kwargs.get('all_xaxislabels',0) 1133 markersize = kwargs.get('markersize',[]) 1134 zorder = kwargs.get('zorder',[]) 1135 alpha = kwargs.get('alpha',[]) 1136 arrows = kwargs.get('arrows',[]) 1137 if inputfiles: 1138 x,y, xerr, yerr = [],[],[],[] 1139 read_input = [DataIO.readCols(f) for f in inputfiles] 1140 for inputfile in read_input: 1141 x.append(inputfile[0]) 1142 y.append(inputfile[1]) 1143 if len(inputfile) == 2: 1144 xerr.append(None) 1145 yerr.append(None) 1146 elif len(inputfile) == 3: 1147 xerr.append(inputfile[2]) 1148 yerr.append(None) 1149 elif len(inputfile) == 4: 1150 if set(list(inputfile[3])) != set([0]): 1151 yerr.append(inputfile[3]) 1152 else: 1153 yerr.append(None) 1154 if set(list(inputfile[2])) != set([0]): 1155 xerr.append(inputfile[2]) 1156 else: 1157 xerr.append(None) 1158 elif len(inputfile) == 6: 1159 if set(list(inputfile[2])) != set([0]) \ 1160 or set(list(inputfile[3])) != set([0]): 1161 xerr.append([inputfile[2],inputfile[3]]) 1162 else: 1163 xerr.append(None) 1164 if set(list(inputfile[4])) != set([0]) \ 1165 or set(list(inputfile[5])) != set([0]): 1166 yerr.append([inputfile[4],inputfile[5]]) 1167 else: 1168 yerr.append(None) 1169 else: 1170 print 'WARNING! Inputfiles have wrong number of columns. ' + \ 1171 'Aborting.' 1172 return 1173 if not list(x) or not list(y): 1174 print 'WARNING: No x and/or y input defined! Skipping plotting.' 1175 return 1176 pl.rc('text', usetex=True) 1177 pl.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) 1178 try: 1179 dummy = len(y[0]) 1180 y = [array(yi) for yi in y] 1181 except TypeError: 1182 y = [array(y)] 1183 try: 1184 dummy = len(x[0]) 1185 if len(y) == len(x): 1186 x = [array(xi) for xi in x] 1187 else: 1188 raise TypeError 1189 except TypeError: 1190 x = [array(x) for yi in y] 1191 keytags = list(keytags) 1192 #if len(keytags) != len(x) and keytags: keytags = [] 1193 keytags = [k.replace(';',',') for k in keytags] 1194 labels = [(l1.replace(';',','),l2,l3) for l1,l2,l3 in labels] 1195 #labels = [(l1.replace('{','('),l2,l3) for l1,l2,l3 in labels] 1196 #labels = [(l1.replace('}',')'),l2,l3) for l1,l2,l3 in labels] 1197 if len(xerr) != len(x) and xerr: xerr = [] 1198 if len(yerr) != len(y) and yerr: yerr = [] 1199 if len(xerr) > len(yerr): yerr = [None]*len(xerr) 1200 if len(yerr) > len(xerr): xerr = [None]*len(yerr) 1201 if not xerr and not yerr: xerr,yerr = [None]*len(x), [None]*len(y) 1202 if number_subplots != 1: 1203 delta = (x[0][-1] - x[0][0])/float(number_subplots) 1204 # Figure properties 1205 figprops = dict(figsize=figsize) 1206 # Subplot properties 1207 #adjustprops=dict(left=0.1,bottom=0.1,right=0.97,top=0.93,wspace=0.2,hspace=0.2) 1208 # New figure 1209 fig = pl.figure(**figprops) 1210 fig.subplots_adjust(hspace=hspace) 1211 fig.subplots_adjust(bottom=ws_bot) 1212 fig.subplots_adjust(top=ws_top) 1213 fig.subplots_adjust(right=ws_right) 1214 fig.subplots_adjust(left=ws_left) 1215 if transparent: 1216 fig.patch.set_alpha(0.7) 1217 # Tunes the subplot layout 1218 #fig.subplots_adjust(**adjustprops) 1219 extra_line_types = getLineTypes() 1220 line_types,extra_line_types = setLineTypes(len(x),line_types,\ 1221 extra_line_types) 1222 if number_subplots != 1: 1223 twinyaxis = None 1224 xmin = None 1225 xmax = None 1226 if not twinyaxis is None: 1227 twiny_line_types,extra_line_types = setLineTypes(len(twiny_x),\ 1228 twiny_line_types,\ 1229 extra_line_types) 1230 if type(markersize) is types.ListType and len(markersize) != len(x): 1231 markersize = [5]*len(x) 1232 elif not type(markersize) is types.ListType: 1233 markersize = [markersize]*len(x) 1234 1235 if not zorder or len(zorder) != len(x): 1236 zorder = range(len(x)) 1237 1238 if not alpha or len(alpha) != len(x): 1239 alpha = [1]*len(x) 1240 1241 for i in xrange(number_subplots): 1242 sub = pl.subplot(number_subplots, 1, i+1) 1243 these_data = [] 1244 #- Only if number_subplots is not 1, this splitting 1245 #- of data is done. Otherwise, normal plots are made. 1246 if number_subplots != 1: 1247 [these_data.append(\ 1248 [xi[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.)) <= delta/2.],\ 1249 yi[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.)) <= delta/2.],\ 1250 lp,\ 1251 ms,\ 1252 zo,\ 1253 alph,\ 1254 not xerri is None \ 1255 and (type(xerri[0]) is not types.ListType \ 1256 and list(xerri[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.))\ 1257 <= delta/2.]) \ 1258 or [list(xerrii[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.))\ 1259 <= delta/2.]) 1260 for xerrii in xerri]) \ 1261 or None,\ 1262 not yerri is None \ 1263 and (type(xerri[0]) is not types.ListType \ 1264 and list(yerri[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.))\ 1265 <= delta/2.]) \ 1266 or [list(yerrii[abs(xi-(xi[0]+(2*(i+1)-1)*delta/2.))\ 1267 <= delta/2.]) 1268 for yerrii in yerri]) \ 1269 or None]) 1270 for xi,yi,lp,ms,zo,alph,xerri,yerri in zip(x,y,line_types,markersize,zorder,alpha,xerr,yerr) 1271 if list(yi)] 1272 else: 1273 [these_data.append([xi,yi,lp,ms,zo,alph,xerri,yerri]) 1274 for xi,yi,lp,ms,zo,alph,xerri,yerri in zip(x,y,line_types,markersize,zorder,alpha,xerr,yerr) 1275 if list(yi)] 1276 no_err = [] 1277 for index,(xi,yi,lp,ms,zo,alph,xerri,yerri) in enumerate(these_data): 1278 ls,col = splitLineType(lp) 1279 if index in histoplot: 1280 leg, = sub.step(xi,yi,ls,where='mid',ms=ms,\ 1281 linewidth=(thick_lw_data and linewidth*2. \ 1282 or linewidth),\ 1283 markeredgewidth=markeredgewidth,zorder=zo,\ 1284 alpha=alph,color=col,label='dummy') 1285 else: 1286 leg, = sub.plot(xi,yi,ls,linewidth=linewidth,ms=ms,\ 1287 markeredgewidth=markeredgewidth,zorder=zo,\ 1288 alpha=alph,color=col,label='dummy') 1289 if '--' in lp: 1290 leg.set_dashes([8,3]) 1291 if '.-' in lp or '-.' in lp: 1292 leg.set_dashes([8,3,2,3]) 1293 if not xerri is None: 1294 try: 1295 test = len(xerri[0]) 1296 lls = xerri[0] 1297 if len(xerri) == 1: 1298 uls = xerri[0] 1299 else: 1300 uls = xerri[1] 1301 except TypeError: 1302 lls = xerri 1303 uls = xerri 1304 for (ll,ul,xii,yii) in zip(lls,uls,xi,yi): 1305 if ll != 0 or ul != 0: 1306 sub.errorbar(x=[xii],y=[yii],xerr=[[ll],[ul]],\ 1307 ecolor=col,\ 1308 lolims=ll==0,\ 1309 uplims=ul==0,\ 1310 fmt="none",\ 1311 capsize=xerr_capsize,\ 1312 markeredgewidth=xerr_markeredgewidth,\ 1313 elinewidth=xerr_linewidth,\ 1314 barsabove=True,zorder=zo,alpha=alph) 1315 if not yerri is None: 1316 try: 1317 test = len(yerri[0]) 1318 lls = yerri[0] 1319 if len(yerri) == 1: 1320 uls = yerri[0] 1321 else: 1322 uls = yerri[1] 1323 except TypeError: 1324 lls = yerri 1325 uls = yerri 1326 for (ll,ul,xii,yii) in zip(lls,uls,xi,yi): 1327 if ll != 0 or ul != 0: 1328 sub.errorbar(x=[xii],y=[yii],yerr=[[ll],[ul]],\ 1329 ecolor=col,\ 1330 lolims=ll==0,\ 1331 uplims=ul==0,\ 1332 fmt="none",\ 1333 capsize=yerr_capsize,\ 1334 markeredgewidth=yerr_markeredgewidth,\ 1335 elinewidth=yerr_linewidth,\ 1336 barsabove=False,zorder=zo,alpha=alph) 1337 sub.autoscale_view(tight=True,scaley=False) 1338 if xlogscale: 1339 sub.set_xscale('log') 1340 if ylogscale: 1341 sub.set_yscale('log') 1342 if line_labels: 1343 xtemp = [xi for xi in x if xi.size][0] 1344 if number_subplots != 1: 1345 xmin = xtemp[0] + i*delta 1346 xmax = xtemp[0] + (i+1)*delta 1347 #these_labels = [label 1348 #for label in line_labels 1349 #if label[1] <= xtemp[0] + (i+1)*delta 1350 #and label[1] >= xtemp[0] + i*delta] 1351 else: 1352 xmin = xtemp[0] 1353 xmax = xtemp[-1] 1354 #these_labels = [label 1355 #for label in line_labels 1356 #if label[1] <= xtemp[-1] 1357 #and label[1] >= xtemp[0]] 1358 y_pos = max([max(yi) for yi in y if list(yi)])*1.3 1359 setLineLabels(line_labels=line_labels,y_pos=y_pos,\ 1360 line_label_spectrum=line_label_spectrum,\ 1361 line_label_color=line_label_color,\ 1362 line_label_lines=line_label_lines,\ 1363 baseline_line_labels=baseline_line_labels,\ 1364 fontsize_label=fontsize_label,\ 1365 no_line_label_text=no_line_label_text,\ 1366 short_label_lines=short_label_lines,\ 1367 line_label_types=line_label_types,\ 1368 linewidth=line_label_linewidth,xmin=xmin,xmax=xmax,\ 1369 line_label_dashedvib=line_label_dashedvib) 1370 pl.ylabel(yaxis,fontsize=fontsize_axis) 1371 if i == 0: 1372 pl.title(plot_title,fontsize=fontsize_title) 1373 if keytags: 1374 keytags = [keys for keys,yi in zip(keytags,y) if list(yi)] 1375 #if keytags: 1376 #these_tags = [keys for keys,yi in zip(keytags,y) if list(yi)] 1377 #lg = pl.legend(tuple(these_tags),loc=key_location,prop=\ 1378 #pl.matplotlib.font_manager.FontProperties(size=fontsize_key)) 1379 #lg.legendPatch.set_alpha(0.0) 1380 if i == number_subplots-1 or all_xaxislabels: 1381 pl.xlabel(xaxis,fontsize=fontsize_axis) 1382 ax = pl.gca() 1383 if vert_lines: 1384 for x_coord in vert_lines: 1385 ax.axvline(x=x_coord,linewidth=2, ls='--', color='k') 1386 if horiz_lines: 1387 for y_coord in horiz_lines: 1388 ax.axhline(y=y_coord, linewidth=2, ls='--',color='k') 1389 if horiz_rect: 1390 for y1,y2,col in horiz_rect: 1391 ax.axhspan(y1,y2,facecolor=str(col),alpha=0.8) 1392 if vert_rect: 1393 for x1,x2,col in vert_rect: 1394 ax.axvspan(x1,x2,facecolor=str(col),alpha=0.8,zorder=-400) 1395 if labels: 1396 for s,xpos,ypos in labels: 1397 pl.text(xpos,ypos,s,transform=ax.transAxes,\ 1398 fontsize=fontsize_label) 1399 if localized_labels: 1400 ll_xmin = min([sorted(dd[0])[0] for dd in these_data]) 1401 ll_xmax = max([sorted(dd[0])[-1] for dd in these_data]) 1402 for s,xpos,ypos,col in localized_labels: 1403 if xpos < ll_xmax and xpos > ll_xmin: 1404 pl.text((xpos-ll_xmin)/(ll_xmax-ll_xmin),ypos,s,\ 1405 transform=ax.transAxes,\ 1406 fontsize=fontsize_localized_label,\ 1407 color=col) 1408 if arrows: 1409 ll_xmin = min([sorted(dd[0])[0] for dd in these_data]) 1410 ll_xmax = max([sorted(dd[0])[-1] for dd in these_data]) 1411 for x0,y0,dx,dy,w,fc,zo in arrows: 1412 if x0 < ll_xmax and x0 > ll_xmin: 1413 arr = pl.Arrow(x0,y0,dx,dy,width=w,zorder=zo) 1414 arr.set_facecolor(fc) 1415 ax.add_patch(arr) 1416 1417 if removeYvalues: 1418 ax.set_yticks([]) 1419 if removeXvalues: 1420 ax.set_xticks([]) 1421 for label in ax.xaxis.get_ticklabels() + ax.yaxis.get_ticklabels(): 1422 label.set_fontsize(fontsize_ticklabels) 1423 if bold_ticklabels: 1424 label.set_fontweight('bold') 1425 for tl in sub.get_xticklines() + sub.get_yticklines(): 1426 tl.set_markersize(size_ticklines) 1427 tl.set_markeredgewidth(1.2) 1428 for tl in sub.yaxis.get_minorticklines() + sub.xaxis.get_minorticklines(): 1429 tl.set_markersize(size_ticklines/2.) 1430 tl.set_markeredgewidth(1.2) 1431 pl.axes(ax) 1432 if transparent: 1433 ax.patch.set_alpha(0.5) 1434 if not ymin is None: 1435 pl.ylim(ymin=ymin) # min([min(xi) for xi in x]) 1436 if not ymax is None: 1437 pl.ylim(ymax=ymax) 1438 1439 #-- Add a twin y axis if needed. 1440 if not twinyaxis is None: 1441 sub2 = sub.twinx() 1442 twindata = [] 1443 [twindata.extend([xi,yi,lp]) 1444 for xi,yi,lp in zip(twiny_x,twiny_y,twiny_line_types) 1445 if list(yi)] 1446 sub2.plot(linewidth=linewidth,label='dummy',*twindata) 1447 sub2.autoscale_view(tight=True,scaley=False) 1448 if twiny_logscale: 1449 sub2.set_yscale('log') 1450 if twiny_ymin is None: 1451 twiny_ymin = 0.9*min([min(yi) for yi in twiny_y]) 1452 pl.ylim(ymin=twiny_ymin) # min([min(xi) for xi in x]) 1453 if twiny_ymax is None: 1454 twiny_ymax = 1.1*max([max(yi) for yi in twiny_y]) 1455 pl.ylim(ymax=twiny_ymax) 1456 if twiny_keytags: 1457 twiny_keytags = [keys 1458 for keys,yi in zip(twiny_keytags,twiny_y) 1459 if list(yi)] 1460 sub2.set_ylabel(twinyaxis,fontsize=fontsize_axis) 1461 for label in sub2.xaxis.get_ticklabels() + sub2.yaxis.get_ticklabels(): 1462 label.set_fontsize(fontsize_ticklabels) 1463 if bold_ticklabels: 1464 label.set_fontweight('bold') 1465 for tl in sub2.get_xticklines() + sub2.get_yticklines(): 1466 tl.set_markersize(size_ticklines) 1467 tl.set_markeredgewidth(1.2) 1468 for tl in sub2.yaxis.get_minorticklines() + sub2.xaxis.get_minorticklines(): 1469 tl.set_markersize(size_ticklines/2.) 1470 tl.set_markeredgewidth(1.2) 1471 1472 #-- Set the x min max after the twin axis was added. 1473 if not xmin is None: 1474 pl.xlim(xmin=xmin) # min([min(xi) for xi in x]) 1475 if not xmax is None: 1476 pl.xlim(xmax=xmax) 1477 1478 #-- Set the keytags. Only done for the first subplot in case a split 1479 # spectrum is plotted. 1480 if i == 0 and keytags: 1481 subs = [sub] 1482 1483 #-- Extract the dummy keytags which we replace here 1484 klines, klabels = sub.get_legend_handles_labels() 1485 1486 #-- Perhaps fewer keys required than the number of lines 1487 klines = klines[:len(keytags)] 1488 1489 #-- Add the keytags for the twin y axis 1490 if twiny_keytags: 1491 twinklines, klabels = sub2.get_legend_handles_labels() 1492 twinklines = twinklines[:len(twiny_keytags)] 1493 klines += twinklines 1494 keytags += twiny_keytags 1495 subs.append(sub2) 1496 1497 #-- Always use the last axis for the legend 1498 prop = pl.matplotlib.font_manager.FontProperties(size=fontsize_key) 1499 lg = subs[-1].legend(klines, keytags, loc=key_location,prop=prop,\ 1500 numpoints=legend_numpoints) 1501 lg.legendPatch.set_alpha(0.8) 1502 lg.set_zorder(max(zorder)+1) 1503 1504 if filename: filename = saveFig(filename,extension,landscape) 1505 if show_plot or filename is None: 1506 pl.subplots_adjust(bottom=0.10) 1507 pl.subplots_adjust(top=0.95) 1508 pl.subplots_adjust(right=0.95) 1509 pl.subplots_adjust(left=0.10) 1510 pl.show() 1511 pl.close('all') 1512 return filename
1513 1514 1515
1516 -def saveFig(filename,extension='pdf',landscape=0):
1517 1518 ''' 1519 Save a figure to a filename for a given extension. 1520 1521 @param filename: The full path+filename of the figure, except the extension 1522 @type filename: str 1523 @keyword extension: The extension of the figure requested. Can be a list. If 1524 None, figures are saved in .pdf, .png, and .eps. 1525 1526 (default: pdf) 1527 @type extension: list(str) 1528 @keyword landscape: Save the figure in landscape mode. 1529 1530 (default: 0) 1531 @type landscape: bool 1532 1533 @return: The full filename with extension 1534 @rtype: str 1535 1536 ''' 1537 1538 if not extension: 1539 extension = ['pdf','png','eps'] 1540 elif isinstance(extension,str): 1541 extension = [extension] 1542 for ext in extension: 1543 fn = filename + os.path.extsep + ext.strip('.') 1544 pl.savefig(fn,orientation=('landscape' if landscape else 'portrait')) 1545 return fn
1546 1547 1548
1549 -def setLineTypes(n,line_types,extra_line_types=None):
1550 1551 ''' 1552 Set the line types for this plot. 1553 1554 If they are given as input, nothing is changed. 1555 1556 If the input is wrong, they are given by default values. 1557 1558 Zeroes in the input are also replaced by defaults. 1559 1560 @param n: Number of line types requested in total 1561 @type n: list[array] 1562 @param line_types: The input value for the line_types 1563 @type line_types: list[string] 1564 @param extra_line_types: The pool of extra line_types, which is destroyed 1565 as defaults are used. If None, they are auto 1566 generated at first. 1567 1568 (default: None) 1569 @type extra_line_types: list[string] 1570 1571 @return: The set line types and default pool of line types (possibly 1572 smaller than the input value) 1573 @rtype: (list[string],list[string]) 1574 1575 ''' 1576 1577 if not extra_line_types: 1578 extra_line_types = getLineTypes() 1579 if type(line_types) is types.StringType: 1580 line_types=[line_types] 1581 elif not type(line_types) is types.ListType: 1582 line_types=[] 1583 if len(line_types) == 1: 1584 line_types *= n 1585 elif not line_types or len(line_types) != n: 1586 if n > len(extra_line_types): 1587 raise IOError('Too many datasets for plotting requested with resp'+\ 1588 'ect to the amount of extra line types available.') 1589 line_types = extra_line_types[:n] 1590 extra_line_types = [extra for extra in extra_line_types 1591 if extra not in line_types] 1592 line_types = [lp and str(lp) or extra_line_types.pop(0) 1593 for lp in line_types] 1594 return (line_types,extra_line_types)
1595 1596 1597
1598 -def setLineLabels(line_labels,line_label_spectrum,fontsize_label,y_pos,\ 1599 line_label_color,line_label_lines,baseline_line_labels,\ 1600 no_line_label_text,short_label_lines,line_label_types,\ 1601 linewidth,xmin,xmax,line_label_dashedvib):
1602 1603 ''' 1604 Set the line labels in a plot. 1605 1606 @param line_labels: The line labels to be set including 1607 (labels,x_pos,mol_index,vibrational) 1608 @type line_labels: list(tuple) 1609 @param line_label_spectrum: linelabels are set at the top and bottom of 1610 the spectrum, as for PACS spectra. If 2, all 1611 labels are set at the top. 1612 @type line_label_spectrum: bool 1613 @param fontsize_label: fontsize of the labels 1614 @type fontsize_label: int 1615 @param y_pos: The y position of the label if line_label_spectrum is False 1616 @type y_pos: float 1617 @param line_label_color: Color the line labels and lines 1618 @type line_label_color: bool 1619 @param line_label_lines: Draw vertical lines at the label 1620 @type line_label_lines: bool 1621 @param baseline_line_labels: Put the line labels at the baseline or the 1622 bottom of the plot 1623 @type baseline_line_labels: bool 1624 @param no_line_label_text: Don't show text for line labels, only lines are 1625 shown if requested. 1626 @type no_line_label_text: bool 1627 @param short_label_lines: The label lines are short and at the top of plot 1628 @type short_label_lines: bool 1629 @param line_label_types: The line types for the line label lines. 1630 @type line_label_types: list 1631 @param linewidth: line width of the line label lines. 1632 @type linewidth: int 1633 @param xmin: The minimum allowed x value for the line labels 1634 @type xmin: float 1635 @param xmax: The maximum allowed x value for the line labels 1636 @type xmax: float 1637 @param line_label_dashedvib: Use dashed lines for vibrational transitions 1638 in line label lines. Only applied if the 1639 ground state label line is a full line. 1640 @type line_label_dashedvib: bool 1641 1642 ''' 1643 1644 #-- Sort the indices, so that the order is always ascending. For line labels 1645 # in spectroscopy/molecule identification this means the order follows 1646 # Molecule.dat for the molecules, followed by fn_trans_marker labels and 1647 # undetected labels. This is also the order to follow when defining your 1648 # own line_label_types. 1649 all_indices = sorted(set([index for label,x_pos,index,vib in line_labels])) 1650 1651 #-- Set the line types for these indices 1652 extra_ls = getLineTypes(black=not line_label_color) 1653 ltd = dict() 1654 for ii,this_i in enumerate(all_indices): 1655 if len(all_indices) != len(line_label_types): 1656 ltd[this_i] = extra_ls[ii] 1657 else: 1658 ltd[this_i] = line_label_types[ii] 1659 1660 #-- Select labels based on the x-range. 1661 allowed_labels = [label 1662 for label in line_labels 1663 if label[1] <= xmax and label[1] >= xmin] 1664 1665 #-- Set the line label tags if requested 1666 if not no_line_label_text: 1667 for l,(label,x_pos,index,vib) in enumerate(allowed_labels): 1668 if line_label_spectrum == 2: 1669 pl.text(x_pos,pl.axis()[3],label,\ 1670 ha=line_label_lines and 'right' or 'center',\ 1671 rotation='vertical',\ 1672 fontsize=fontsize_label,\ 1673 color=splitLineType(ltd[index])[1]) 1674 elif line_label_spectrum: 1675 pl.text(x_pos,l%2==0 and pl.axis()[3] or pl.axis()[2],label,\ 1676 va=baseline_line_labels \ 1677 and (l%2==0 and 'top' or 'baseline') \ 1678 or (l%2==0 and 'top' or 'bottom'),\ 1679 ha=line_label_lines and 'right' or 'center',\ 1680 rotation='vertical',\ 1681 fontsize=fontsize_label,\ 1682 color=splitLineType(ltd[index])[1]) 1683 else: 1684 pl.text(x_pos,l%2==0 and pl.axis()[2] or y_pos,label,\ 1685 va=baseline_line_labels \ 1686 and (l%2==0 and 'top' or 'baseline') \ 1687 or (l%2==0 and 'top' or 'bottom'),\ 1688 ha=line_label_lines and 'right' or 'center',\ 1689 rotation='vertical',\ 1690 fontsize=fontsize_label,\ 1691 color=splitLineType(ltd[index])[1]) 1692 1693 #-- Draw the line label lines if requested 1694 if line_label_lines: 1695 for label,x_pos,index,vib in allowed_labels: 1696 if line_label_dashedvib and vib \ 1697 and splitLineType(ltd[index])[0] == '-': 1698 ls = '--' 1699 else: 1700 ls = splitLineType(ltd[index])[0] 1701 pl.axvline(x=x_pos,\ 1702 ymin=short_label_lines and 0.7 or 0,ls=ls,\ 1703 c=splitLineType(ltd[index])[1],\ 1704 linewidth=linewidth,zorder=-100)
1705 1706 1707
1708 -def getLineTypes(black=0):
1709 1710 ''' 1711 Make linetypes from a list of colors and line types. 1712 1713 @keyword black: Return only black colors 1714 1715 (Default: 0) 1716 @type black: bool 1717 1718 @return: The linetypes 1719 @rtype: list(str) 1720 1721 ''' 1722 1723 linestyles = ['-','--','-.',':','x','o',':','s','.','+','h','d','|','p','2'] 1724 linestyles += linestyles + linestyles 1725 colors = ['k'] if black else ['r','b','k','g','m','y','c'] 1726 return [ls + col for ls in linestyles for col in colors ]
1727 1728 1729
1730 -def splitLineType(lp):
1731 1732 ''' 1733 Split a line style string in its color and line type components. 1734 1735 Note that grayscale values should always be given as a four-character 1736 string that represents a float between 0 and 1. 1737 1738 @param lp: the line type string, eg '.-k' 1739 @type lp: string 1740 @return: two string, the first giving the line type, the second the color 1741 @rtype: string, string 1742 1743 ''' 1744 1745 linetype = '' 1746 color = '' 1747 for char in lp: 1748 if char in ['r','b','k','g','m','y','c','w','0']: 1749 if char == '0': 1750 color += lp[lp.index(char):lp.index(char)+4] 1751 else: 1752 color += char 1753 break 1754 linetype = lp.replace(color,'',1) 1755 return linetype,color
1756 1757 1758
1759 -def makeHistoPlot(x,y,indices=[]):
1760 1761 ''' 1762 [DEPRECATED] -- not used by Plotting2 anymore. 1763 1764 Convert x and y data into input for an unbinned 'histogram' plot. 1765 1766 (by Pieter de Groote) 1767 1768 @param x: input x-values 1769 @type x: list[array/list] 1770 @param y: input y-values 1771 @type y: list[array/list] 1772 @keyword indices: Make a histogram plot if list is not empty. 1773 List holds indices of input data lists for the ones that 1774 will be shaped as a histogram. 1775 The others will be plotted as normal. 1776 1777 default: [] 1778 @type indices: list[int] 1779 @return: the converted x and y data -- xo, yo 1780 @rtype: list[array], list[array] 1781 1782 ''' 1783 1784 xo, yo = [], [] 1785 indices = [int(i) for i in indices] 1786 for i,(xi,yi) in enumerate(zip(x,y)): 1787 if i in indices: 1788 xoi = pl.zeros(2*len(xi)) 1789 yoi = pl.zeros(2*len(xi)) 1790 xoi[1:-1:2] = xi[:-1]+pl.diff(xi)/2. 1791 xoi[:-2:2] = xi[:-1]-pl.diff(xi)/2. 1792 xoi[-1] = xi[-1]+(xi[-1]-xi[-2])/2. 1793 xoi[-2] = xi[-1]-(xi[-1]-xi[-2])/2. 1794 yoi[::2] = yi 1795 yoi[1::2] = yi 1796 xo.append(xoi) 1797 yo.append(yoi) 1798 else: 1799 xo.append(xi) 1800 yo.append(yi) 1801 return xo,yo
1802 1803 1804
1805 -def readCfg(cfg):
1806 1807 ''' 1808 Read a cfg file. 1809 1810 @param cfg: path to the config file. If default, 1811 the hard-coded default plotting options are used. 1812 @type cfg: string 1813 1814 @return: The contents of the cfg file are returned. 1815 @rtype: dict 1816 1817 ''' 1818 1819 if cfg: 1820 cfg_dict = DataIO.readDict(cfg,convert_lists=1,convert_floats=1) 1821 else: 1822 cfg_dict = dict() 1823 1824 return cfg_dict
1825