Changeset 1553 in lmdz_wrf for trunk


Ignore:
Timestamp:
May 2, 2017, 7:07:24 PM (8 years ago)
Author:
lfita
Message:

Adding `draw_time_lag': Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)

Location:
trunk/tools
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/documentation/plotting/gallery.html

    r1550 r1553  
    3636      <A HREF="subbasin.html"><IMG SRC="figs/Caceres_subbasin.png" ALT="plot sub-basin from ORCHIDEE's routing" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>     
    3737      <A HREF="Taylor.html"><IMG SRC="figs/Taylor.png" ALT="Taylor diagram" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
     38      <A HREF="time_lag.html"><IMG SRC="figs/mon1_timelag_pr-evap_SACZ.png" ALT="Time lag" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
     39      <A HREF="time_lag.html"><IMG SRC="figs/mon1_timelag_pr-evap_SACZ_shadline.png" ALT="Time lag" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
     40      <A HREF="time_lag.html"><IMG SRC="figs/mon1_timelag_pr-evap_SACZ_epeatPeriod.png" ALT="Time lag" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
    3841      <A HREF="TimeSeries.html"><IMG SRC="figs/TimeSeries_ua.png" ALT="Time Series" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
    3942      <A HREF="topo_geogrid.html"><IMG SRC="figs/geo_domain.png" ALT="topography WRF's geogrid" STYLE="float:left;width:200px;height:200px" TARGET="value"></IMG></A>
  • trunk/tools/documentation/plotting/plotting.html

    r1549 r1553  
    3131      <A CLASS="lc" HREF="Taylor.html" TARGET="value">Taylor diagram</A><BR>
    3232      <A CLASS="lc" HREF="TimeSeries.html" TARGET="value">TimeSeries</A><BR>
     33      <A CLASS="lc" HREF="time_lag.html" TARGET="value">Time lag</A><BR>
    3334      <A CLASS="lc" HREF="topo_geogrid.html" TARGET="value">topo geogrid</A><BR>
    3435      <A CLASS="lc" HREF="topo_geogrid_boxes.html" TARGET="value">topo geogrid boxes</A><BR>
  • trunk/tools/drawing.py

    r1550 r1553  
    4949## e.g. # drawing.py -o draw_bar_line -f 'Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SESA_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;bar:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,0@12@1;time_counter;rainnorm;line:Forcing_rainstats_OKstomate_CRUNCEP_spinup_SACZ_norm_meanstd_stat2.nc;time_counter,12@24@1;time_counter;rainnorm;line' -S 'Stringlist,%s,January@Feburary@March@April@May@June@July@August@September@October@November@December@Jan@Feb@Mar@Apr@May@Jun@Jul@Aug@Sept@Oct@Nov@Dec,25,pretty,auto,auto,auto:time!since!1958-01-01:pr:x:-4.,4.:seconds:1:$SESA_{1958}$,$SESA_{1959}$,$SACZ_{1958}$,$SACZ_{1959}$:#AA0000,#0000AA:1000000.:#00AA00,#AAAA00:-.:,:2.:2.:all:normalized!evolution!of!precipitation!with!CRU-NCEP!forcing:0|10:png:bar-line_rain_CRU-NCEP_norm:yes'
    5050## e.g. # drawing.py -o draw_bar_line_time -f 'Forcing_rainstats_OKstomate_SESA_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:Forcing_rainstats_OKstomate_SACZ_DJFmean_norm_meanstd_stat2.nc;time_centered,-1;time_centered;rainnorm;bar:DiPolo_evapstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SESA_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line:DiPolo_evapstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evap_stats;line:DiPolo_evapnustats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evapnu_stats;line:DiPolo_evspsblvegstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;evspsblveg_stats;line:DiPolo_transpirstats_OKstomate_SACZ_DJFmean_stat2.nc;time_centered,-1;time_centered;transpir_stats;line' -S 'auto;pr;y;None;1;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ,SESA!evap,evapnu,evspblveg,transpir,SACZ!evap,None,None,None;#AA0000,#0000AA;10000000.;#AAAA00,#00AAAA,#AA00AA,#AAAAAA,#AAAA00,#00AAAA,#AA00AA,#AAAAAA;-,-,-,-,--,--,--,--;,;2.;2.;all;normalized!evolution!of!DJFmean!with!WFD3!forcing;0|10;png;bar_time_rain_CRU-NCEP_DJFmean_norm;yes'
     51## e.g. # drawing.py -o draw_time_lag -f 'Forcing_rainstats_OKstomate_SESA_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SESA_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm:Forcing_rainstats_OKstomate_SACZ_norm_meanstd_stat2.nc;time_centered,-1;time_counter;rainnorm%DiPolo_evapstats_SACZ_norm_meanstd_OKstomate.nc;time_counter,-1|stats,2;time_counter;evapnorm' -S 'auto;centered;pr;1;evap;1;-5,5;-2,2;year|seconds!since!1958-01-01!00:00:00|exct,5,y|%Y;SESA,SACZ;simplepts,1,#AA0000@#0000AA,x,2.;1-month!time-lag!at!SACZ!between!pr!&!evap!normalized!by!mean/stddev;0|12;png;mon1_timelag_pr-evap_SACZ;yes'
     52
    5153#######
    5254# create_movie: Function to create a movie assuming ImageMagick installed!
     
    7274# draw_points: Function to plot a series of points
    7375# draw_points_lonlat: Function to plot a series of lon/lat points
    74 # draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar
     76# draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar
     77# draw_time_lag: Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)
    7578# draw_timeSeries: Function to draw a time-series
    7679# draw_topo_geogrid: plotting geo_em.d[nn].nc topography from WPS files
     
    102105  'draw_points', 'draw_points_lonlat',                                               \
    103106  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_Taylor',                 \
    104   'draw_timeSeries', 'draw_topo_geogrid',                                            \
     107  'draw_time_lag', 'draw_timeSeries', 'draw_topo_geogrid',                           \
    105108  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
    106109  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'draw_WindRose',         \
     
    65946597        [yunits]: units of the y-label
    65956598        [aval]: which acis should be used for the values ('x' or 'y')
    6596         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     6599        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    65976600         [vmin],[vmax]: minimum and maximum values
    65986601           'auto': the computed minimumm or maximum of the values 
     
    68106813        [yunits]: units of the y-label
    68116814        [aval]: which acis should be used for the values ('x' or 'y')
    6812         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     6815        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    68136816         [vmin],[vmax]: minimum and maximum values
    68146817           'auto': the computed minimumm or maximum of the values 
     
    70237026        [yunits]: units of the y-label
    70247027        [aval]: which acis should be used for the values ('x' or 'y')
    7025         [rangevals]: Range of the axis with the values (singel 'None' for 'auto','auto')
     7028        [rangevals]: Range of the axis with the values (single 'None' for 'auto','auto')
    70267029         [vmin],[vmax]: minimum and maximum values
    70277030           'auto': the computed minimumm or maximum of the values 
     
    72497252    return
    72507253
     7254def draw_time_lag(ncfile, values):
     7255    """ Function to plot a time-lag figure with multiple sources (x, previous values; y, future values)
     7256      ncfile = ':' list of couples ('%' formed) [prefilen];[predslice];[pretvarn];[prevarn]%[futfilen];
     7257          [futdslice];[futtvarn];[futvarn]
     7258        'pre': values to act as previous values
     7259        'fut': values to act as future values
     7260
     7261        [filen]: name of the file
     7262        [dimslice]: '|' list of [dimn],[dimrange]
     7263          [dimn]: name of the dimension
     7264          [dimrange]: range for the slice
     7265            * [integer]: which value of the dimension
     7266            * -1: all along the dimension
     7267            * -9: last value of the dimension
     7268            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
     7269            * NOTE, no dim name all the dimension size
     7270        [tvarn]: name of the variable time
     7271        [yvarn]: name of the variable to use for the values
     7272      values = [dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];[futunits];[prerangevals];
     7273          [futrangevals];[timevals];[labels];[figlagkind];[graphtit];[legvalues];[kindfig];[fign];[close]
     7274        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordy]: format of the values at each
     7275            axis (or single 'auto' for 'auto','auto')
     7276          [dxs]: style of x-axis ('auto' for 'pretty')
     7277            'Nfix', values computed at even 'Ndx'
     7278            'Stringlist', a given list of strings
     7279            'Vfix', values computed at even 'Ndx' increments
     7280            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
     7281          [dxf]: format of the labels at the x-axis
     7282          [Ndx]: Number of ticks at the x-axis (for 'Stringlist', '@' list of labels)
     7283          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
     7284          [dys]: style of y-axis ('auto' for 'pretty')
     7285          [dyf]: format of the labels at the y-axis
     7286          [Ndy]: Number of ticks at the y-axis
     7287          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
     7288        [axeskind]: type of axes to be plotted
     7289          'centered': crossed at 0,0 at the center of the figure
     7290          'box': around the figure
     7291        [preaxislab]: Label for the future-axis ('!' for spaces)
     7292        [preunits]: units of the future-label
     7293        [futaxislab]: Label for the future-axis ('!' for spaces)
     7294        [futunits]: units of the future-label
     7295        [prerangevals]: Range of the previous axis with the values (single 'None' for 'auto','auto')
     7296         [vmin],[vmax]: minimum and maximum values
     7297           'auto': the computed minimumm or maximum of the values 
     7298        [futrangevals]: Range of the future axis with the values (single 'None' for 'auto','auto')
     7299         [vmin],[vmax]: minimum and maximum values
     7300           'auto': the computed minimumm or maximum of the values 
     7301        [timevals]: [timen]|[units]|[kind]|[tfmt] time labels characteristics
     7302          [timen]; name of the time variable
     7303          [units]; units string according to CF conventions ([tunits] since
     7304            [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
     7305          [kind]; kind of output
     7306            'Nval': according to a given number of values as 'Nval',[Nval]
     7307            'exct': according to an exact time unit as 'exct',[tunit];
     7308              tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
     7309               'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
     7310               'l': milisecond
     7311          [tfmt]; desired format
     7312        [labels]: ',' list of labels for the legend ('None' for no-labels, '!' for spaces)
     7313        [figlagkind]=[kindname],[valueskind] kind of time-lag plot
     7314          'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]:
     7315              time-lag for a given repeating sub-period, Line-conected points following a colorbar and time-values
     7316            [Nlag]: number of time steps as lag
     7317            [period]: period to be repeated allover the time-data
     7318            [colorbar]: name of the color bar to use ('auto' for rainbow)
     7319            [cbarfmt]: format of the numbers in the colorbar
     7320            [cbaror]: orientation of the colorbar ('auto' for vertical)
     7321            [ltype]: type of the lines (single value for the same, or 'auto')
     7322            [lsize]: width of the lines (single value for the same, or 'auto')
     7323            [mtype]: type of the markers (single value for the same, or 'auto')
     7324            [msize]: size of the markers (single value for the same, or 'auto')
     7325          'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: Line-conected
     7326              points following a colorbar and time-values
     7327            [Nlag]: number of time steps as lag
     7328            [colorbar]: name of the color bar to use ('auto' for rainbow)
     7329            [cbarfmt]: format of the numbers in the colorbar
     7330            [cbaror]: orientation of the colorbar ('auto' for vertical)
     7331            [ltype]: type of the lines (single value for the same, or 'auto')
     7332            [lsize]: width of the lines (single value for the same, or 'auto')
     7333            [mtype]: type of the markers (single value for the same, or 'auto')
     7334            [msize]: size of the markers (single value for the same, or 'auto')
     7335          'simplepts',[Nlag],[col],[type],[size]: Simple points assuming that values have all the same times
     7336            [Nlag]: number of time steps as lag
     7337            [col]: '@' list of colors of the points (single value for the same, or 'auto')
     7338            [type]:types of the points (single value for the same, or 'auto')
     7339            [size]: sizes of the points kind of lag-time figure (single value for the same, or 'auto')
     7340      labels= list of labels for legend (None for no legend, and 'None' for no specific label)
     7341        [graphtit]: title of the figure '!' for spaces
     7342        [legvalues]=[locleg]|[fontsize]:
     7343          [locleg]: location of the legend (0, autmoatic)
     7344            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     7345            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     7346            9: 'upper center', 10: 'center'
     7347          [fontsize]: font size for the legend (auto for 12)
     7348        [kindfig]: kind of output figure (png, pdf, ps)
     7349        [fign]: name of the figure (without extension)
     7350        [close]: whether figure should be close or not
     7351    """
     7352    fname = 'draw_time_lag'
     7353
     7354    if values == 'h':
     7355        print fname + '____________________________________________________________'
     7356        print draw_time_lag.__doc__
     7357        quit()
     7358
     7359    expectargs = '[dimxyfmt];[axeskind];[preaxislab];[preunits];[futaxislab];' +     \
     7360      '[futunits];[prerangevals];[futrangevals];[timevals];[labels];[figlagkind];' + \
     7361      '[graphtit];[legvalues];[kindfig];[fign];[close]'
     7362    drw.check_arguments(fname,values,expectargs,';')
     7363
     7364    dimxyfmt = values.split(';')[0]
     7365    axeskind = values.split(';')[1]
     7366    preaxislab = values.split(';')[2].replace('!',' ')
     7367    preunits = values.split(';')[3]
     7368    futaxislab = values.split(';')[4].replace('!',' ')
     7369    futunits = values.split(';')[5]
     7370    prerangevals = values.split(';')[6]
     7371    futrangevals = values.split(';')[7]
     7372    timevals = values.split(';')[8]
     7373    labels = gen.str_list(values.split(';')[9].replace('!', ' '), ',')
     7374    figlagkind = values.split(';')[10]
     7375    graphtit = values.split(';')[11].replace('!',' ')
     7376    legvalues = values.split(';')[12]
     7377    kindfig = values.split(';')[13]
     7378    fign = values.split(';')[14]
     7379    close = gen.Str_Bool(values.split(';')[15])
     7380
     7381    # files and values
     7382    filedvs = ncfile.split(':')
     7383    timevalues = []
     7384    prevalues = []
     7385    futvalues = []
     7386
     7387    # time-values
     7388    expectargs = '[timen]|[units]|[kind]|[tfmt]'
     7389    drw.check_arguments('timevals: '+fname,timevals,expectargs,'|')
     7390
     7391    timen = timevals.split('|')[0].replace('!',' ')
     7392    timeunit = timevals.split('|')[1].replace('!',' ')
     7393    timekind = timevals.split('|')[2]
     7394    timefmt = timevals.split('|')[3]
     7395
     7396    preminval = gen.fillValue
     7397    premaxval = -gen.fillValue
     7398    futminval = gen.fillValue
     7399    futmaxval = -gen.fillValue
     7400    mintval = gen.fillValue
     7401    maxtval = -gen.fillValue
     7402
     7403    for fdvprefut in filedvs:
     7404        prefutdv = fdvprefut.split('%')
     7405        ifile=0
     7406        for fdv in prefutdv:
     7407            filen = fdv.split(';')[0]
     7408            dimrange = fdv.split(';')[1]
     7409            tvarn = fdv.split(';')[2]
     7410            yvarn = fdv.split(';')[3]
     7411            futfdv = fdvprefut.split('%')[1]
     7412
     7413            if not os.path.isfile(filen):
     7414                print errormsg
     7415                print '  ' + fname + ': file "' + filen + '" does not exist !!'
     7416                quit(-1)
     7417
     7418            onc = NetCDFFile(filen, 'r')
     7419            if not onc.variables.has_key(tvarn):
     7420                print errormsg
     7421                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
     7422                  tvarn + "' for the time-values !!"
     7423                print '    available ones:', onc.variables.keys()
     7424                onc.close()
     7425                quit(-1)
     7426            if not onc.variables.has_key(yvarn):
     7427                print errormsg
     7428                print '  ' +fname+ ': file "' +filen+ "' does not have variable '" + \
     7429                  yvarn + "' for the y-values !!"
     7430                print '    available ones:', onc.variables.keys()
     7431                onc.close()
     7432                quit(-1)
     7433
     7434            otvar = onc.variables[tvarn]
     7435            oyvar = onc.variables[yvarn]
     7436            tvs, tdims = ncvar.slice_variable(otvar, dimrange.replace(',',':'))
     7437            yvs, ydims = ncvar.slice_variable(oyvar, dimrange.replace(',',':'))
     7438            tunitsvar = otvar.units
     7439
     7440            if len(tvs.shape) != 1:
     7441                print errormsg
     7442                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
     7443                  tvarn + "' does not provide a rank-1 value !!"
     7444                print '    resultant shape:', tvs.shape, 'dimensions:',tdims,'fix it!!'
     7445                quit(-1)
     7446            if len(yvs.shape) != 1:
     7447                print errormsg
     7448                print '  ' +fname+ ': provided slice:', dimrange, "for variable '" + \
     7449                  yvarn + "' does not provide a rank-1 value !!"
     7450                print '    resultant shape:',yvs.shape, 'dimensions:',ydims,'fix it!!'
     7451                quit(-1)
     7452   
     7453            uvd = timeunit
     7454            tunitsec = timeunit.split(' ')
     7455            if len(tunitsec) == 4:
     7456                refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +      \
     7457                  tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
     7458            else:
     7459                refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +      \
     7460                  '000000'
     7461            tunitsval = tunitsec[0]
     7462            # Referring all times to the same reference time!
     7463            reftvals = gen.coincident_CFtimes(tvs, timeunit, tunitsvar)
     7464     
     7465            onc.close()
     7466
     7467            reftn = reftvals.min()
     7468            reftx = reftvals.max()
     7469            if reftn < mintval: mintval = reftn
     7470            if reftx > maxtval: maxtval = reftx
     7471
     7472            if ifile == 0:
     7473                timevalues.append(reftvals)
     7474                prevalues.append(yvs)
     7475                pren = yvs.min()
     7476                prex = yvs.max()
     7477                if pren < preminval: preminval = pren
     7478                if prex > premaxval: premaxval = prex
     7479            else:
     7480                timevalues.append(reftvals)
     7481                futvalues.append(yvs)
     7482                futn = yvs.min()
     7483                futx = yvs.max()
     7484                if futn < futminval: futminval = futn
     7485                if futx > futmaxval: futmaxval = futx
     7486            ifile = ifile + 1
     7487
     7488    # Times
     7489    if figlagkind[0:12] == 'repeatPeriod':
     7490        per=int(figlagkind.split(',')[2])
     7491        dtvals = (maxtval - mintval)/10/per
     7492    else:
     7493        dtvals = (maxtval - mintval)/10
     7494    dti = mintval
     7495    dte = maxtval
     7496    tvalsticks = np.arange(dti, dte+dtvals, dtvals)
     7497
     7498    dtiS = drw.datetimeStr_conversion(str(dti) + ',' + timeunit, 'cfTime',           \
     7499     'Y/m/d H-M-S')
     7500    dteS = drw.datetimeStr_conversion(str(dte) + ',' + timeunit, 'cfTime',           \
     7501     'Y/m/d H-M-S')
     7502
     7503    print '  ' + fname + ': plotting from: ' + dtiS + ' to ' + dteS
     7504
     7505    timepos, timelabels = drw.CFtimes_plot(tvalsticks, timeunit, timekind, timefmt)
     7506
     7507    # ranges
     7508    if prerangevals == 'None':
     7509        valmin = preminval
     7510        valmax = premaxval
     7511    else:
     7512        if prerangevals.split(',')[0] != 'auto':
     7513            valmin = np.float(prerangevals.split(',')[0])
     7514        else:
     7515            valmin = preminval
     7516        if prerangevals.split(',')[1] != 'auto':
     7517            valmax = np.float(prerangevals.split(',')[1])
     7518        else:
     7519            valmax = premaxval
     7520    prerng = [valmin, valmax]
     7521
     7522    if futrangevals == 'None':
     7523        valmin = futminval
     7524        valmax = futmaxval
     7525    else:
     7526        if futrangevals.split(',')[0] != 'auto':
     7527            valmin = np.float(futrangevals.split(',')[0])
     7528        else:
     7529            valmin = futminval
     7530        if futrangevals.split(',')[1] != 'auto':
     7531            valmax = np.float(futrangevals.split(',')[1])
     7532        else:
     7533            valmax = futmaxval
     7534    futrng = [valmin, valmax]
     7535
     7536    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
     7537    xaxis = [xstyl, xaxf, Nxax, xaxor]
     7538    yaxis = [ystyl, yaxf, Nyax, yaxor]
     7539
     7540    # Legend
     7541    legloc, legsiz = drw.legend_values(legvalues,'|')
     7542
     7543    drw.plot_time_lag(prevalues, futvalues, timevalues, xaxis, yaxis, axeskind,      \
     7544      preaxislab, futaxislab, preunits, futunits, prerng, futrng, figlagkind, labels,\
     7545      timen, timepos, timelabels, graphtit, legloc, legsiz, kindfig, fign, close)
     7546
     7547    return
    72517548
    72527549#quit()
     
    72737570  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
    72747571  'draw_bar', 'draw_bar_line', 'draw_bar_line_time', 'draw_bar_time', 'draw_lines',  \
    7275   'draw_lines_time', 'draw_points', 'draw_Taylor', 'draw_topo_geogrid_boxes',        \
     7572  'draw_lines_time', 'draw_points', 'draw_Taylor', 'draw_time_lag',                  \
     7573  'draw_topo_geogrid_boxes',                                                         \
    72767574  'draw_trajectories', 'draw_vals_trajectories', 'variable_values']
    72777575
     
    73627660    elif oper == 'draw_Taylor':
    73637661        draw_Taylor(opts.ncfile, opts.values, opts.varname)
     7662    elif oper == 'draw_time_lag':
     7663        draw_time_lag(opts.ncfile, opts.values)
    73647664    elif oper == 'draw_timeSeries':
    73657665        draw_timeSeries(opts.ncfile, opts.values, opts.varname)
  • trunk/tools/drawing_tools.py

    r1550 r1553  
    7676# plot_2D_shadow_time: Plotting a 2D field with one of the axes being time
    7777# plot_Neighbourghood_evol:Plotting neighbourghood evolution
     78# plot_time_lag: Function to plot a time-lag figure (x, previous values; y, future values)
    7879# plot_Trajectories
    7980# plot_2D_shadow_contour:
     
    17691770        print "  the standard 'rainbow' will be use instead !!"
    17701771        print '    colorbars availables with this version:', maps
     1772        quit(-1)
    17711773
    17721774    return
     
    98279829        plt.yticks(dimyt, list(dimyl), rotation=yaxv[3])
    98289830        plt.xlabel(gen.latex_text(xlabel))
    9829         plt.ylabel(ylabel + ' (' + units_lunits(dimyu) + ')')
     9831        plt.ylabel(gen.latex_text(ylabel) + ' (' + units_lunits(dimyu) + ')')
    98309832        plt.ylim(dyn, dyx)
    98319833
     
    98399841    return
    98409842
    9841 
     9843def plot_time_lag(prevals, futvals, tvals, xaxv, yaxv, axistype, prelab, futlab,     \
     9844  preu, futu, prerange, futrange, figtype, labels, tname, tpos, tlab, gtit, lloc,    \
     9845  lsiz, kfig, figname, ifclose):
     9846    """ Function to plot a time-lag figure (x, previous values; y, future values)
     9847      prevals= list with the previous values
     9848      futvals= list with future values
     9849      tavals= list of time-values (common for couples)
     9850      [x/y]axv= values at the axes x and y
     9851      axistype: type of axis to be plotted
     9852        'centered': crossed at 0,0 at the center of the figure
     9853        'box': around the figure
     9854      [pre/fut]lab= variable label at previous and future-axis
     9855      [pre/fut]u= units of the previous and future variable-axis
     9856      [pre/fut]range: ranges of the revious and future variable-axis
     9857      figtype= [kindname],[valueskind] kind of time-lag plot
     9858        'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]:
     9859            time-lag for a given repeating sub-period, Line-conected points following a colorbar and time-values
     9860          [Nlag]: number of time steps as lag
     9861          [period]: period to be repeated allover the time-data
     9862          [colorbar]: name of the color bar to use ('auto' for rainbow)
     9863          [cbarfmt]: format of the numbers in the colorbar
     9864          [cbaror]: orientation of the colorbar ('auto' for vertical)
     9865          [ltype]: type of the lines (single value for the same, or 'auto')
     9866          [lsize]: width of the lines (single value for the same, or 'auto')
     9867          [mtype]: type of the markers (single value for the same, or 'auto')
     9868          [msize]: size of the markers (single value for the same, or 'auto')
     9869       'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror],[ltype],[lwidth],[mtype],[msize]: Line-conected
     9870            points following a colorbar and time-values
     9871          [Nlag]: number of time steps as lag
     9872          [colorbar]: name of the color bar to use ('auto' for rainbow)
     9873          [cbarfmt]: format of the numbers in the colorbar
     9874          [cbaror]: orientation of the colorbar ('auto' for vertical)
     9875          [ltype]: type of the lines (single value for the same, or 'auto')
     9876          [lsize]: width of the lines (single value for the same, or 'auto')
     9877          [mtype]: type of the markers (single value for the same, or 'auto')
     9878          [msize]: size of the markers (single value for the same, or 'auto')
     9879        'simplepts',[Nlag],[col],[type],[size]: Simple points assuming that values have all the same times
     9880          [Nlag]: number of time steps as lag
     9881          [col]: color of the points (single value for the same, or 'auto')
     9882          [type]:type of the markers (single value for the same, or 'auto')
     9883          [size]: size of the markers (single value for the same, or 'auto')   
     9884      labels= list of labels for legend (None for no legend, and 'None' for no specific label)
     9885      tname= label of the time-axis
     9886      tpos= position of the time-ticks
     9887      tlab= labels of the time-ticks
     9888      gtit= title of the figure
     9889      lloc= location of the legend (0, autmoatic)
     9890        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     9891        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     9892        9: 'upper center', 10: 'center'
     9893      lsiz= font size of the legend
     9894      kfig= kind of output: pdf, png, ps
     9895      figname= name of the figure
     9896      ifclose= whether figure should be closed
     9897    """
     9898    fname = 'plot_time_lag'
     9899
     9900    Nvalues = len(prevals)
     9901
     9902    dxn = gen.fillValue
     9903    dxx = -gen.fillValue
     9904    dyn = gen.fillValue
     9905    dyx = -gen.fillValue
     9906
     9907    for iv in range(Nvalues):
     9908        minv = np.min(prevals[iv])
     9909        maxv = np.max(prevals[iv])
     9910        if minv < dxn: dxn = minv
     9911        if maxv > dxx: dxx = maxv
     9912        minv = np.min(futvals[iv])
     9913        maxv = np.max(futvals[iv])
     9914        if minv < dyn: dyn = minv
     9915        if maxv > dyx: dyx = maxv
     9916
     9917    axstyles = ['pretty', 'Nfix', 'Stringlist', 'Vfix']
     9918    if xaxv[0] == 'pretty':
     9919        dimxt = np.array(gen.pretty_int(dxn,dxx,xaxv[2]))
     9920        dimxl = np.array(dimxt, dtype=str)
     9921    elif xaxv[0] == 'Nfix':
     9922        dimxl = np.arange(dxn,dxx,(dxx-dxn)/(xaxv[2]+1))
     9923        dimxt = np.arange(dxn,dxx,(dxx-dxn)/Lxmaxvals)
     9924    elif xaxv[0] == 'Stringlist':
     9925        if len(xaxv[2]) != len(xticks):
     9926            print warnmsg
     9927            print '  ' + fname + ': number of ticks to plot=', len(xticks),         \
     9928              'and number of labels provided', len(xaxv[2]), 'differ !!'
     9929            print '  ' + fname + ': ticks to plot=', xticks, 'and provided labels', \
     9930                xaxv[2], 'differ !!'
     9931
     9932        dimxl = xaxv[2]
     9933        dimxt = xticks
     9934    elif xaxv[0] == 'Vfix':
     9935        dxnvfix = int(dxn/xaxv[2])
     9936        dimxt = np.arange(dxnvfix*xaxv[2],dxx,xaxv[2])
     9937    else:
     9938        print errormsg
     9939        print '  ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!"
     9940        print '    available ones: ', axstyles
     9941        quit(-1)
     9942
     9943    if yaxv[0] == 'pretty':
     9944        dimyt = np.array(gen.pretty_int(dyn,dyx,yaxv[2]))
     9945        dimyl = np.array(dimyt, dtype=str)
     9946    elif yaxv[0] == 'Nfix':
     9947        dimyt = np.arange(dyn,dyx,(dyx-dyn)/(yaxv[2]+1))
     9948        dimyl = np.arange(dyn,dyx,(dyx-dyn)/Lymaxvals)
     9949        axytype='fixpixel'
     9950    elif yaxv[0] == 'Vfix':
     9951        dynvfix = int(dyn/yaxv[2])
     9952        dimyt = np.arange(dynvfix*xaxv[2],dyx,yaxv[2])
     9953        axytype='data'
     9954    else:
     9955        print errormsg
     9956        print '  ' + fname + ": x-xais style '" + xaxv[0] + "' not ready !!"
     9957        print '    available ones: ', axstyles
     9958        quit(-1)
     9959
     9960    # kind of time-lag figure:
     9961    figv = figtype.split(',')
     9962    figtypen = figv[0]
     9963
     9964    plt.rc('text', usetex=True)
     9965    fig, ax = plt.subplots(1)
     9966
     9967    for iv in range(Nvalues):
     9968        xvs = np.array(prevals[iv])
     9969        yvs = np.array(futvals[iv])
     9970        try:
     9971            with gen.Capturing() as output:
     9972                gen.same_shape(np.array(xvs), np.array(yvs))
     9973        except:
     9974            print errormsg
     9975            print '  ' + fname + ': shape of matrix from couple:', iv, 'differ !!'
     9976            for sout in output: print sout
     9977            quit(-1)
     9978
     9979        dimt = xvs.shape[0]
     9980        tvalues = tvals[iv]
     9981        if figtypen == 'repeatPeriod':
     9982            expectargs = "'repeatPeriod',[Nlag],[period],[colorbar],[cbarfmt]," +    \
     9983              "[cbaror],[ltype],[lwidth],[mtype],[msize]"
     9984            check_arguments(fname + " & 'repeatPeriod'",figtype,expectargs,',')
     9985
     9986            Nlag = int(figv[1])
     9987            period = int(figv[2])
     9988            colbar = gen.auto_val(figv[3], 'rainbow')
     9989            check_colorBar(colbar)
     9990            cbarfmt = figv[4]
     9991            cbaror = gen.auto_val(figv[5], 'vertical')
     9992            ltype = gen.str_list_rep(figv[6],'@',Nvalues)
     9993            lwidth = gen.str_list_rep(figv[7],'@',Nvalues)
     9994            mtype = gen.str_list_rep(figv[8],'@',Nvalues)
     9995            msize = gen.str_list_rep(figv[9],'@',Nvalues)
     9996
     9997            my_cmap = plt.cm.get_cmap(colbar)
     9998            Nperiods = dimt/period
     9999            tminv = np.min(tvals[iv])
     10000            tmaxv = np.max(tvals[iv])
     10001            norm = mpl.colors.Normalize(0.,Nperiods)
     10002
     10003            # Normalizing position of the ticks
     10004            if iv == 0:
     10005                tpos = tpos*Nperiods/tmaxv
     10006
     10007            if labels is not None and labels[iv] != 'None':
     10008                for ip in range(Nperiods):
     10009                    clv = my_cmap(norm(ip*1.))
     10010                    for it in range(period+Nlag):
     10011                        Tt = period*ip+it
     10012                        if Tt + Nlag + 1 > dimt-1: break
     10013                        if ip == 0 and it == 0:
     10014                            plt.plot([xvs[Tt],xvs[Tt+1]], [yvs[Tt+Nlag],yvs[Tt+Nlag+1]], \
     10015                              ltype[iv], color=clv, linewidth=np.float(lwidth[iv]),      \
     10016                              marker=mtype[iv], markersize=np.float(msize[iv]),          \
     10017                              label=gen.latex_text(labels[iv]))
     10018                        else:
     10019                            plt.plot([xvs[Tt],xvs[Tt+1]], [yvs[Tt+Nlag],yvs[Tt+Nlag+1]], \
     10020                              ltype[iv], color=clv, linewidth=np.float(lwidth[iv]),      \
     10021                              marker=mtype[iv], markersize=np.float(msize[iv]))
     10022            else:
     10023                for ip in range(Nperiods):
     10024                    clv = my_cmap(norm(ip*1.))
     10025                    for it in range(period+Nlag):
     10026                        Tt = period*ip+it
     10027                        if Tt + Nlag + 1 > dimt-1: break
     10028                        plt.plot([xvs[it], xvs[it+1]], [yvs[it+Nlag], yvs[it+Nlag+1]],   \
     10029                          ltype[iv], color=clv, linewidth=lwidth[iv], marker=mtype[iv],  \
     10030                          markersize=msize[iv])
     10031        elif figtypen == 'shadTline':
     10032            expectargs = "'shadTline',[Nlag],[colorbar],[cbarfmt],[cbaror]," +       \
     10033              "[ltype],[lwidth],[mtype],[msize]"
     10034            check_arguments(fname + " & 'shadTline'",figtype,expectargs,',')
     10035
     10036            Nlag = int(figv[1])
     10037            colbar = gen.auto_val(figv[2], 'rainbow')
     10038            check_colorBar(colbar)
     10039            cbarfmt = figv[3]
     10040            cbaror = gen.auto_val(figv[4], 'vertical')
     10041            ltype = gen.str_list_rep(figv[5],'@',Nvalues)
     10042            lwidth = gen.str_list_rep(figv[6],'@',Nvalues)
     10043            mtype = gen.str_list_rep(figv[7],'@',Nvalues)
     10044            msize = gen.str_list_rep(figv[8],'@',Nvalues)
     10045
     10046            my_cmap = plt.cm.get_cmap(colbar)
     10047            tminv = np.min(tvals[iv])
     10048            tmaxv = np.max(tvals[iv])
     10049            norm = mpl.colors.Normalize(tminv,tmaxv)
     10050
     10051            if labels is not None and labels[iv] != 'None':
     10052                for it in range(dimt-Nlag-1):
     10053                    clv = my_cmap(norm(tvalues[it]))
     10054                    if it == 0:
     10055                        plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]], \
     10056                          ltype[iv], color=clv, linewidth=np.float(lwidth[iv]),      \
     10057                          marker=mtype[iv], markersize=np.float(msize[iv]),          \
     10058                          label=gen.latex_text(labels[iv]))
     10059                    else:
     10060                        plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]], \
     10061                          ltype[iv], color=clv, linewidth=np.float(lwidth[iv]),      \
     10062                          marker=mtype[iv], markersize=np.float(msize[iv]))
     10063            else:
     10064                for it in range(dimt-Nlag):
     10065                    clv = my_cmap(norm(it))       
     10066                    plt.plot([xvs[it],xvs[it+1]], [yvs[it+Nlag],yvs[it+Nlag+1]],     \
     10067                      ltype[iv], color=clv, linewidth=lwidth[iv], marker=mtype[iv],  \
     10068                      markersize=msize[iv])
     10069        elif figtypen == 'simplepts':
     10070            expectargs = "'simplepts',[Nlag],[col],[type],[size]"
     10071            check_arguments(fname + " & 'simplepts'",figtype,expectargs,',')
     10072
     10073            Nlag = int(figv[1])
     10074            col = gen.str_list_rep(figv[2],'@',Nvalues)
     10075            mark = gen.str_list_rep(figv[3],'@',Nvalues)
     10076            size = gen.str_list_rep(figv[4],'@',Nvalues)
     10077            if labels is not None and labels[iv] != 'None':
     10078                plt.plot(xvs[0:dimt-Nlag], yvs[Nlag:dimt], ',', color=col[iv],       \
     10079                  marker=mark[iv], markersize=size[iv],                              \
     10080                  label=gen.latex_text(labels[iv]))
     10081            else:
     10082                plt.plot(xvs[0:dimt-Nlag], yvs[Nlag:dimt], ',', color=col[iv],       \
     10083                  marker=mark[iv], markersize=size[iv])
     10084        else:
     10085            print errormsg
     10086            print '  ' + fname + ": time-lag figure named '" + figtype + "' not ready !!"
     10087            print '    availabe ones:', ['repeatPeriod', 'shadTline', 'simplepts']
     10088            quit(-1)
     10089
     10090    if axistype == 'box':
     10091        print infmsg
     10092        print '    ' + fname + ': plotting with around axes'
     10093    elif axistype == 'centered':
     10094        # Drawing centered axes
     10095        # From http://stackoverflow.com/questions/31556446/drawing-axis-in-the-middle-of-the-figue-in-python
     10096        # Move left y-axis and bottim x-axis to centre, passing through (0,0)
     10097        ax.spines['left'].set_position('center')
     10098        ax.spines['bottom'].set_position('center')
     10099
     10100        # Eliminate upper and right axes
     10101        ax.spines['right'].set_color('none')
     10102        ax.spines['top'].set_color('none')
     10103    else:
     10104        print errormsg
     10105        print '  ' + fname + ": axis plotting type '" + axistype + "' not ready !!"
     10106        print '    available ones:', ['box', 'centered']
     10107        quit(-1)
     10108
     10109    plt.yticks(dimxt, list(dimxl), rotation=xaxv[3])
     10110    plt.yticks(dimyt, list(dimyl), rotation=yaxv[3])
     10111    if preu != 'None':
     10112        plt.xlabel(gen.latex_text(prelab) + ' (' + units_lunits(preu) + ')')
     10113    else:
     10114        plt.xlabel(gen.latex_text(prelab))
     10115    if futu != 'None':
     10116        plt.ylabel(gen.latex_text(futlab) + ' (' + units_lunits(futu) + ')')
     10117    else:
     10118        plt.xlabel(gen.latex_text(futlab))
     10119
     10120    ax.xaxis.set_label_coords(0.5, -0.025)
     10121    ax.yaxis.set_label_coords(-0.025, 0.5)
     10122
     10123    plt.xlim(prerange[0], prerange[1])
     10124    plt.ylim(futrange[0], futrange[1])
     10125
     10126    if labels is not None:
     10127        plt.legend(loc=lloc, prop={'size':lsiz})
     10128
     10129    # Colorbar
     10130    if gen.searchInlist(['repeatPeriod', 'shadTline'], figtypen):
     10131        # FROM: http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
     10132        # For matplotlib v1.3 or greater the code becomes:
     10133        sm = plt.cm.ScalarMappable(cmap=colbar, norm=norm)
     10134        # fake up the array of the scalar mappable. Urgh...
     10135        sm._A = []
     10136        #cbar = plt.colorbar(sm)
     10137
     10138        if cbaror == 'horizontal':
     10139            cbar = plt.colorbar(sm, ticks=[tpos], format=cbarfmt,orientation=cbaror)
     10140            cbar.ax.set_xticklabels(tlab,rotation=90)
     10141        else:
     10142            print warnmsg
     10143            print '  ' + fname + ": This is odd, because in 'vertical' mode does " + \
     10144              "not work the re-labelling of the ticking!"
     10145            cbar = plt.colorbar(sm, ticks=[tpos], format=cbarfmt, orientation=cbaror)
     10146            cbar.ax.set_xticklabels(tlab)
     10147
     10148        cbar.set_label(gen.latex_text(tname))
     10149
     10150    plt.title(gen.latex_text(gtit))
     10151   
     10152    output_kind(kfig, figname, ifclose)
     10153
     10154    return
     10155
Note: See TracChangeset for help on using the changeset viewer.