Changeset 1077 in lmdz_wrf for trunk


Ignore:
Timestamp:
Sep 1, 2016, 6:47:35 PM (9 years ago)
Author:
lfita
Message:

Adding `draw_2lines_time:' Function to plot two time-lines in different axes (x/x2 or y/y2)

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r1074 r1077  
    3333## e.g. # drawing.py -o draw_subbasin -f Caceres_subbasin.nc -S 'Caceres:None:cyl,l:2,True:Caceres:pdf:0:Caceres_subbasin'
    3434## e.g. # drawing.py -o draw_2lines -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_tvar_xmean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_tvar_xmean.nc -v wssvarmean,tasvarmean -S 'lat:0.,20.:0.,4.:-90.,90.:y:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!meridional!tvar:lon:0:wss_tas_wrfout_tvar_xmean:pdf'
     35## e.g. # drawing.py -o draw_2lines_time -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_xvar_ymean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_xvar_ymean.nc -v wssvarmean,tasvarmean -S 'time:0.,20.:0.,4.:exct,1,d;%d:x:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!longitudinal!xvar:time!($[DD]$):0:wss_tas_wrfout_xvar_ymean:pdf'
    3536
    3637main = 'drawing.py'
     
    4344  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
    4445  'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins',                             \
    45   'draw_2lines', 'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol',        \
     46  'draw_2lines', 'draw_2lines_time', 'draw_lines', 'draw_lines_time',                \
     47  'draw_Neighbourghood_evol',                                                        \
    4648  'draw_points', 'draw_points_lonlat',                                               \
    4749  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_timeSeries',             \
     
    42864288      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, figname, figkind)
    42874289
     4290
     4291def draw_2lines_time(ncfiles, values, varnames):
     4292    """ Function to plot two time-lines in different axes (x/x2 or y/y2)
     4293      values= [timevardim]:[varangeA]:[varangeB]:[varangeaxis]:[axisvals]:[figvarns]:[colors]:
     4294       [widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:[labelaxis]:[lloc]:[figname]:[figkind]
     4295        [timevardim]: name of the common variable-dimension time
     4296        [varangeA]: ',' separated list of range (min,max) for A values ('None', automatic; 'Extrs' from values extremes)
     4297        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic; 'Extrs' from values extremes)
     4298        [timeaxisfmt]=[tkind];[tfmt]: format of the ticks for the time axis:
     4299           [kind]: kind of time to appear in the graph
     4300             'Nval': according to a given number of values as 'Nval',[Nval]
     4301             'exct': according to an exact time unit as 'exct',[tunit];
     4302               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
     4303                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
     4304                'l': milisecond
     4305           [tfmt]; desired format
     4306        [timeaxis]: which is the time axis in the plot ('x' or 'y')
     4307        [figvarns]: ',' separated list of names of the variables in the  plot
     4308        [colors]: ',' list with color names of the lines for the variables ('None', automatic)
     4309        [widths]: ',' list with widths of the lines for the variables ('None', automatic)
     4310        [styles]: ',' list with the styles of the lines ('None', automatic)
     4311        [sizemarks]: ',' list with the size of the markers of the lines ('None', automatic)
     4312        [marks]: ',' list with the markers of the lines ('None', automatic)
     4313        [graphtitle]: title of the figure ('!' for spaces)
     4314        [labelaxis]: label in the figure of the common axis ('!' for spaces)
     4315        [lloc]: location of the legend (0, automatic)
     4316          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     4317          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     4318          9: 'upper center', 10: 'center'      kfig= kind of figure
     4319        [figname]: name of the figure
     4320        [figkind]: kind of figure
     4321      ncfiles= ',' separated list of files to use
     4322      varnames=  ',' separated list of variables names in the files to plot
     4323    """
     4324    fname = 'draw_2lines_time'
     4325
     4326    if values == 'h':
     4327        print fname + '_____________________________________________________________'
     4328        print draw_2lines_time.__doc__
     4329        quit()
     4330
     4331    expectargs = '[timevardim]:[varangeA]:[varangeB]:[timeaxisfmt]:[timeaxis]:' +    \
     4332     '[figvarns]:[colors]:[widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:' +     \
     4333     '[labelaxis]:[lloc]:[figname]:[figkind]'
     4334 
     4335    drw.check_arguments(fname,values,expectargs,':')
     4336
     4337    timevardim = values.split(':')[0]
     4338    varangeA0 = values.split(':')[1]
     4339    varangeB0 = values.split(':')[2]
     4340    timeaxisfmt = values.split(':')[3]
     4341    timeaxis = values.split(':')[4]
     4342    figvarns = values.split(':')[5].split(',')
     4343    colors = gen.str_list(values.split(':')[6],',')
     4344    widths = gen.str_list_k(values.split(':')[7],',','np.float')
     4345    styles = gen.str_list(values.split(':')[8],',')
     4346    sizemarks = gen.str_list_k(values.split(':')[9],',','np.float')
     4347    marks = gen.str_list(values.split(':')[10],',')
     4348    graphtitle = values.split(':')[11].replace('!',' ')
     4349    labelaxis = values.split(':')[12].replace('!',' ')
     4350    lloc = np.int(values.split(':')[13])
     4351    figname = values.split(':')[14]
     4352    figkind = values.split(':')[15]
     4353
     4354    files = ncfiles.split(',')
     4355    invarns = varnames.split(',')
     4356
     4357    varunits = []
     4358
     4359    # Values line A
     4360    if not os.path.isfile(files[0]):
     4361        print errormsg
     4362        print '  ' + fname + ": file '" + files[0] + "' does not exist !!"
     4363        quit(-1)
     4364
     4365    oncA = NetCDFFile(files[0], 'r')
     4366
     4367    if not gen.searchInlist(oncA.variables.keys(), invarns[0]):
     4368        print errormsg
     4369        print '  ' + fname + ": A file '" + files[0] + "' does not have variable '" +\
     4370          invarns[0] + "' !!"
     4371        quit(-1)
     4372    if not gen.searchInlist(oncA.variables.keys(), timevardim):
     4373        print errormsg
     4374        print '  ' + fname + ": A file '" + files[0] + "' does not have time " +     \
     4375          "variable '" + timevardim + "' !!"
     4376        quit(-1)
     4377
     4378    objvA = oncA.variables[invarns[0]]
     4379    varvalsA = objvA[:]
     4380    varangeA = np.zeros((2),dtype=np.float)
     4381    objtA = oncA.variables[timevardim]
     4382    timevalsA = objtA[:]
     4383    trangeA = [np.min(timevalsA), np.max(timevalsA)]
     4384    tunitsA = objtA.getncattr('units')
     4385
     4386    if gen.searchInlist(objvA.ncattrs(), 'units'):
     4387        varunits.append(drw.units_lunits(objvA.getncattr('units')))
     4388    else:
     4389        valsA = gen.variables_values(invarns[0])
     4390        varunits.append(drw.units_lunits(valsA[5]))
     4391    if varangeA0 == 'None':
     4392        varangeA = [valsA[2], valsA[3]]
     4393    elif varangeA0 == 'Extrs':
     4394        varangeA = [np.min(varvalsA), np.max(varvalsA)]
     4395    else:
     4396        for iv in range(2): varangeA[iv] = np.float(varangeA0.split(',')[iv])
     4397
     4398    oncA.close()
     4399
     4400    # Values line B
     4401    if not os.path.isfile(files[1]):
     4402        print errormsg
     4403        print '  ' + fname + ": file '" + files[1] + "' does not exist !!"
     4404        quit(-1)
     4405
     4406    oncB = NetCDFFile(files[1], 'r')
     4407
     4408    if not gen.searchInlist(oncB.variables.keys(), invarns[1]):
     4409        print errormsg
     4410        print '  ' + fname + ": B file '" + files[1] + "' does not have variable '" +\
     4411          invarns[1] + "' !!"
     4412        quit(-1)
     4413    if not gen.searchInlist(oncB.variables.keys(), timevardim):
     4414        print errormsg
     4415        print '  ' + fname + ": B file '" + files[1] + "' does not have time " +     \
     4416          "variable '" + timevardim + "' !!"
     4417        quit(-1)
     4418
     4419    objvB = oncB.variables[invarns[1]]
     4420    varvalsB = objvB[:]
     4421    varangeB = np.zeros((2),dtype=np.float)
     4422    objtB = oncB.variables[timevardim]
     4423    timevalsB = objtB[:]
     4424    tunitsB = objtB.getncattr('units')
     4425
     4426    if gen.searchInlist(objvB.ncattrs(), 'units'):
     4427        varunits.append(drw.units_lunits(objvB.getncattr('units')))
     4428    else:
     4429        valsB = gen.variables_values(invarns[1])
     4430        varunits.append(drw.units_lunits(valsB[5]))
     4431    if varangeB0 == 'None':
     4432        varangeB = [valsB[2], valsB[3]]
     4433    elif varangeB0 == 'Extrs':
     4434        varangeA = [np.min(varvalsA), np.max(varvalsA)]
     4435    else:
     4436        for iv in range(2): varangeB[iv] = np.float(varangeB0.split(',')[iv])
     4437   
     4438    oncB.close()
     4439
     4440    # Time axis taking time units in line A as reference
     4441    varvalsaxisB = drw.coincident_CFtimes(timevalsB, tunitsA, tunitsB)
     4442    trangeB = [np.min(varvalsaxisB), np.max(varvalsaxisB)]
     4443
     4444    varangeaxis = [np.min([trangeA[0],trangeB[0]]), np.max([trangeA[1],trangeB[1]])]
     4445
     4446    timevals = np.arange(varangeaxis[0],varangeaxis[1])
     4447    tkind = timeaxisfmt.split(';')[0]
     4448    tformat = timeaxisfmt.split(';')[1]
     4449    tpos, tlabels = drw.CFtimes_plot(timevals, tunitsA, tkind, tformat)
     4450
     4451    # Lines characteristics
     4452    colvalues, linekinds, pointkinds, lwidths, psizes = drw.ColorsLinesPointsStyles( \
     4453      2, colors, styles, marks, widths, sizemarks, 'None')
     4454
     4455    drw.plot_2lines_time(varvalsA, varvalsB, timevalsA, varvalsaxisB, varangeA,      \
     4456      varangeB, tpos, tlabels, timeaxis, figvarns, varunits, colvalues, lwidths,     \
     4457      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, figname, figkind)
     4458
    42884459#quit()
    42894460
     
    43244495# Not checking file operation
    43254496Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time',                    \
    4326   'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_lines',        \
     4497  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
     4498  'draw_lines',                                                                      \
    43274499  'draw_lines_time', 'draw_points', 'draw_topo_geogrid_boxes', 'draw_trajectories',  \
    43284500  'draw_vals_trajectories', 'variable_values']
     
    43624534elif oper == 'draw_2lines':
    43634535    draw_2lines(opts.ncfile, opts.values, opts.varname)
     4536elif oper == 'draw_2lines_time':
     4537    draw_2lines_time(opts.ncfile, opts.values, opts.varname)
    43644538elif oper == 'draw_lines':
    43654539    draw_lines(opts.ncfile, opts.values, opts.varname)
  • trunk/tools/drawing_tools.py

    r1074 r1077  
    6868# plot_2D_shadow_line:
    6969# plot_2lines: Function to plot two lines in different axes (x/x2 or y/y2)
     70# plot_2lines_time: Function to plot two time-lines in different axes (x/x2 or y/y2)
    7071# plot_lines: Function to plot a collection of lines
    7172# plot_ZQradii: Function to plot following radial averages only at exact grid poins
     
    75437544
    75447545    return
     7546
     7547
     7548def plot_2lines_time(valsA, valsB, valsaxisA, valsaxisB, rangeA, rangeB, valstaxis,  \
     7549  labelstaxis, taxis, varns, varus, cols, wdths, styls, szmks, marks, gtitle, axisn, \
     7550  gloc, fign, figk):
     7551    """ Function to plot two time-lines in different axes (x/x2 or y/y2)
     7552      valsA= values to be plotted on axis x or y
     7553      valsB= values to be plotted on axis x2 or y2
     7554      valsaxisA= values at the common axis for valsA
     7555      valsaxisB= values at the common axis for valsB
     7556      rangeA= range of values for valsA
     7557      rangeB= range of values for valsB
     7558      valstaxis= values for the tick in the time-axis
     7559      labelstaxis= labels for the tick in the time-axis
     7560      taxis= which is the axis for the time values ('x' or 'y')
     7561      varns= names of the variables in the  plot
     7562      varus= units of the variables
     7563      cols= list with color names of the lines for the variables
     7564      wdths= list with widths of the lines for the variables
     7565      styls= list with the styles of the lines
     7566      szmks= list with the size of the markers of the lines
     7567      marks= list with the markers of the lines
     7568      gtitle= title of the figure
     7569      axisn= label in the figure of the time axis
     7570      gloc= location of the legend
     7571      fign= name of the figure
     7572      figk= kind of figure
     7573    """
     7574    fname = 'plot_2lines_time'
     7575
     7576    if taxis == 'x':
     7577        titX = axisn
     7578        titX2 = axisn
     7579        titY = varns[0] + ' (' + varus[0] + ')'
     7580        titY2 = varns[1] + ' (' + varus[1] + ')'
     7581        xmin = np.min(valstaxis)
     7582        xmax = np.max(valstaxis)
     7583        ymin = rangeA[0]
     7584        ymax = rangeA[1]
     7585        ymin2 = rangeB[0]
     7586        ymax2 = rangeB[1]
     7587    else:
     7588        titX = varns[0] + ' (' + varus[0] + ')'
     7589        titX2 = varns[1] + ' (' + varus[1] + ')'
     7590        titY = axisn
     7591        titY2 = axisn
     7592        xmin = rangeA[0]
     7593        xmax = rangeA[1]
     7594        xmin2 = rangeB[0]
     7595        xmax2 = rangeB[1]
     7596        ymin = np.min(valstaxis)
     7597        ymax = np.max(valstaxis)
     7598
     7599# From: http://matplotlib.org/examples/api/two_scales.html
     7600    fig, ax1 = plt.subplots()
     7601
     7602    # Plotting lines
     7603    il=0
     7604    if taxis == 'x':
     7605        lA, = ax1.plot(valsaxisA, valsA, styls[il], marker=marks[il],                \
     7606          linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il])
     7607        ax1.set_xlabel(titX, color='black')
     7608        ax1.set_ylabel(titY, color=cols[il])
     7609        ax1.set_xlim(xmin,xmax)
     7610        ax1.set_ylim(ymin,ymax)
     7611        ax1.set_xticks(valstaxis)
     7612        ax1.set_xticklabels(labelstaxis)
     7613
     7614        ax2 = ax1.twinx()
     7615        il = il + 1
     7616        lB, = ax2.plot(valsaxisB, valsB, styls[il], marker=marks[il],                \
     7617          linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il])
     7618        ax2.set_ylabel(titY2, color=cols[il])
     7619        ax2.set_ylim(ymin2,ymax2)
     7620        ax2.set_xlim(xmin,xmax)
     7621        ax2.set_xticks(valstaxis)
     7622        ax2.set_xticklabels(labelstaxis)
     7623        titleloc = (0.5,1.)
     7624    else:
     7625        lA, = ax1.plot(valsA, valsaxisA, styls[il], marker=marks[il],                \
     7626          linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il])
     7627        ax1.set_xlabel(titX, color=cols[il])
     7628        ax1.set_ylabel(titY, color='black')
     7629        ax1.set_xlim(xmin,xmax)
     7630        ax1.set_ylim(ymin,ymax)
     7631        ax1.set_yticks(valstaxis)
     7632        ax1.set_yticklabels(labelstaxis)
     7633
     7634        ax2 = ax1.twiny()
     7635        il = il + 1
     7636        lB, = ax2.plot(valsB, valsaxisB, styls[il], marker=marks[il],                \
     7637          linewidth=wdths[il], markersize=szmks[il], label=varns[il], color=cols[il])
     7638        ax2.set_xlabel(titX2, color=cols[il])
     7639        ax2.set_xlim(xmin2,xmax2)
     7640        ax2.set_ylim(ymin,ymax)
     7641        ax2.set_yticks(valstaxis)
     7642        ax2.set_yticklabels(labelstaxis)
     7643        titleloc = (0.5,1.075)
     7644       
     7645#    graphtit = gtitle.replace('_','\_').replace('&','\&')
     7646    graphtit = gtitle
     7647
     7648    plt.title(graphtit,position=titleloc)
     7649    # plt.legend([lA, lB], loc=gloc)
     7650   
     7651    output_kind(figk, fign, True)
     7652
     7653    return
Note: See TracChangeset for help on using the changeset viewer.