Exemplo n.º 1
0
    def plot_index_t_x_z(self,
                         numb=[],
                         figsize=[],
                         do_subplot=[],
                         do_output=True):
        from set_inputarray import inputarray
        fsize = 16
        #_______________________________________________________________________
        if isinstance(numb, int) == True: numb = [numb]
        if len(numb) == 0: numb = range(0, len(self.box_define))

        #_______________________________________________________________________
        for ii in numb:
            #fig = plt.figure(figsize=(12, 6))
            #ax1  = plt.gca()

            if len(figsize) == 0: figsize = [10, 5]
            #___________________________________________________________________________
            # plot is not part of subplot
            if len(do_subplot) == 0:
                fig = plt.figure(figsize=figsize)
                ax1 = plt.gca()
            else:
                fig = do_subplot[0]
                ax1 = do_subplot[1]
                fig.sca(ax1)
            resolution = 'c'
            fsize = 14

            #___________________________________________________________________
            cnumb = 30
            cmin = np.nanmin(self.value[ii])
            cmax = np.nanmax(self.value[ii])
            cref = cmin + (cmax - cmin) / 2
            cref = np.around(cref,
                             -np.int32(np.floor(np.log10(np.abs(cref))) - 1))
            #cref =0.0

            #___________________________________________________________________
            # if anomaly data
            if self.anom == True:
                cmax, cmin, cref = np.nanmax(self.value[ii]), np.nanmin(
                    self.value[ii]), 0.0
                self.cmap = 'blue2red'
            #___________________________________________________________________
            # if predefined color range
            if len(self.crange) != 0:
                if len(self.crange) == 2:
                    cmin = np.float(self.crange[0])
                    cmax = np.float(self.crange[1])
                    cref = np.around(
                        cref, -np.int32(np.floor(np.log10(np.abs(cref))) - 1))
                elif len(self.crange) == 3:
                    cmin = np.float(self.crange[0])
                    cmax = np.float(self.crange[1])
                    cref = np.float(self.crange[2])
                else:
                    print(' this colorrange definition is not supported !!!')
                    print(
                        'data.crange=[cmin,cmax] or data.crange=[cmin,cmax,cref]'
                    )

            if do_output == True:
                print('[cmin,cmax,cref] = [' + str(cmin) + ', ' + str(cmax) +
                      ', ' + str(cref) + ']')
            if do_output == True: print('[cnum]=', cnumb)
            cmap0, clevel = colormap_c2c(cmin, cmax, cref, cnumb, self.cmap)
            if do_output == True: print('clevel = ', clevel)

            do_drawedges = True
            if clevel.size > 50: do_drawedges = False

            # overwrite discrete colormap
            #cmap0 = cmocean.cm.balance
            #do_drawedges=False

            #___________________________________________________________________
            # make pcolor or contour plot
            #depth = self.depth[:-1] + (self.depth[1:]-self.depth[:-1])/2.0
            #depth = self.zlev[:-1] + (self.zlev[1:]-self.zlev[:-1])/2.0
            depth = -self.zlev
            depthlim = np.sum(~np.isnan(self.value[ii][0, :])).max()
            if depthlim == depth.shape: depthlim = depthlim - 1
            yy, xx = np.meshgrid(depth, self.time)

            #___________________________________________________________________
            data_plot = np.copy(self.value[ii])
            data_plot[data_plot < clevel[0]] = clevel[0] + np.finfo(
                np.float32).eps
            data_plot[data_plot > clevel[-1]] = clevel[-1] - np.finfo(
                np.float32).eps

            #___________________________________________________________________
            if inputarray['which_plot'] == 'pcolor':
                hp = ax1.pcolormesh(
                    xx[:, 0:depthlim],
                    yy[:, 0:depthlim],
                    data_plot[:, 0:depthlim],
                    shading='flat',  #flat
                    antialiased=False,
                    edgecolor='None',
                    cmap=cmap0),
                #vmin=np.nanmin(data_plot), vmax=np.nanmax(data_plot))
            else:
                hp = ax1.contourf(xx[:, 0:depthlim],
                                  yy[:, 0:depthlim],
                                  data_plot[:, 0:depthlim],
                                  levels=clevel,
                                  antialiased=True,
                                  cmap=cmap0,
                                  vmin=clevel[0],
                                  vmax=clevel[-1])
                ax1.contour(xx[:, 0:depthlim],
                            yy[:, 0:depthlim],
                            data_plot[:, 0:depthlim],
                            levels=clevel,
                            antialiased=True,
                            colors='k',
                            linewidths=[0.25, 0.1],
                            linestyles=['solid'],
                            vmin=np.nanmin(data_plot),
                            vmax=np.nanmax(data_plot))
            #hp.cmap.set_under([0.4,0.4,0.4])

            #___________________________________________________________________
            # set main axes
            ax1.set_xlim(self.time.min(), self.time.max())
            ax1.set_ylim(0, depth[depthlim - 1])
            ax1.invert_yaxis()
            #ax1.set_axis_bgcolor([0.25,0.25,0.25])
            ax1.tick_params(axis='both',
                            which='major',
                            direction='out',
                            length=8,
                            labelsize=fsize)
            ax1.minorticks_on()
            ax1.tick_params(axis='both',
                            which='minor',
                            direction='out',
                            length=4,
                            labelsize=fsize)
            ax1.set_xlabel('Time [years]', fontdict=dict(fontsize=fsize))
            ax1.set_ylabel('Depth [km]', fontdict=dict(fontsize=fsize))
            plt.title(self.descript + ' - ' + self.box_define[0][2],
                      fontdict=dict(fontsize=fsize * 2),
                      verticalalignment='bottom')

            #___________________________________________________________________
            # draw colorbar
            #divider = make_axes_locatable(ax1)
            #cax     = divider.append_axes("right", size="2.5%", pad=0.5)
            #plt.clim(clevel[0],clevel[-1])
            him = ax1.get_images()
            for im in ax1.get_images():
                im.set_clim(clevel[0], clevel[-1])

            #cbar = plt.colorbar(hp,ax=ax1,cax=cax,ticks=clevel,drawedges=do_drawedges)
            cbar = plt.colorbar(hp,
                                ax=ax1,
                                ticks=clevel,
                                drawedges=do_drawedges)
            cbar.set_label(self.lname + ' ' + self.unit + '\n' + self.str_time,
                           size=fsize)

            cl = plt.getp(cbar.ax, 'ymajorticklabels')
            plt.setp(cl, fontsize=fsize)

            # kickout some colormap labels if there are to many
            ncbar_l = len(cbar.ax.get_yticklabels()[:])
            idx_cref = np.where(clevel == cref)[0]
            idx_cref = np.asscalar(idx_cref)
            nmax_cbar_l = 10
            nstep = ncbar_l / nmax_cbar_l
            nstep = np.int(np.floor(nstep))
            #plt.setp(cbar.ax.get_yticklabels()[:], visible=False)
            #plt.setp(cbar.ax.get_yticklabels()[idx_cref::nstep], visible=True)
            #plt.setp(cbar.ax.get_yticklabels()[idx_cref::-nstep], visible=True)
            if nstep == 0: nstep = 1
            tickl = cbar.ax.get_yticklabels()
            idx = np.arange(0, len(tickl), 1)
            idxb = np.ones((len(tickl), ), dtype=bool)
            idxb[idx_cref::nstep] = False
            idxb[idx_cref::-nstep] = False
            idx = idx[idxb == True]
            for ii in list(idx):
                tickl[ii] = ''
            cbar.ax.set_yticklabels(tickl)

            # reposition colorbar and axes
            plt.tight_layout()
            pos_ax = ax1.get_position()
            ax1.set_position(
                [pos_ax.x0, pos_ax.y0, 0.90 - pos_ax.y0, pos_ax.height])
            pos_ax = ax1.get_position()
            pos_cbar = cbar.ax.get_position()
            cbar.ax.set_position([
                pos_ax.x0 + pos_ax.width + 0.01, pos_cbar.y0, pos_cbar.width,
                pos_cbar.height
            ])
            fig.canvas.draw()
            #___________________________________________________________________
            # save figure
            if inputarray['save_fig'] == True:
                print(' --> save figure: png')
                str_times = self.str_time.replace(' ', '').replace(':', '')
                str_deps = self.str_dep.replace(' ', '').replace(',',
                                                                 '').replace(
                                                                     ':', '')
                sfname = 'boxplot_' + self.box_define[ii][
                    2] + '_' + self.descript + '_' + self.sname + '_' + str_times + '_' + str_deps + '.png'
                sdname = inputarray['save_figpath']
                if os.path.isdir(sdname) == False: os.mkdir(sdname)
                plt.savefig(sdname+sfname, \
                            format='png', dpi=600, \
                            bbox_inches='tight', pad_inches=0,\
                            transparent=True,frameon=True)
            #___________________________________________________________________
            plt.show(block=False)
            print('finish')

        return (fig, ax1, cbar)
Exemplo n.º 2
0
def plot_xmoc(lat,
              depth,
              moc,
              bottom=[],
              which_moc='gmoc',
              str_descript='',
              str_time='',
              figsize=[],
              crange=[],
              cnumb=20,
              do_clabel=True,
              do_subplot=[]):

    #___________________________________________________________________________
    if len(figsize) == 0: figsize = [13, 6]

    #___________________________________________________________________________
    # plot is not part of subplot
    if len(do_subplot) == 0:
        fig = plt.figure(figsize=figsize)
        ax1 = plt.gca()
    else:
        fig = do_subplot[0]
        ax1 = do_subplot[1]

    resolution = 'c'
    fsize = 10
    txtx, txty = lat[0] + 5, depth[-1] + 100

    #+_________________________________________________________________________+
    #| set minimum, maximum and reference values for the creation of the       |
    #| adjustable colormap                                                     |
    #+_________________________________________________________________________+
    #cnumb = 20; # minimum number of colors
    #cmin,cmax,cref  = -6,16,0 # [cmin, cmax, cref]  --> MLD2
    cmin, cmax, cref = moc[np.where(depth <= -500)[0][0]::, :].min(
    ), moc[np.where(
        depth <= -500)[0][0]::, :].max(), 0.0  # [cmin, cmax, cref]  --> MLD2
    if len(crange) != 0: cmin, cmax, cref = crange[0], crange[1], 0.0
    print(cmin, cmax, cref)
    cmap0, clevel = colormap_c2c(cmin, cmax, cref, cnumb, 'blue2red')
    cbot = [0.5, 0.5, 0.5]
    do_drawedges = True
    if clevel.size > 30: do_drawedges = False

    #+_________________________________________________________________________+
    #| plot AXES1                                                              |
    #+_________________________________________________________________________+
    plt.sca(ax1)
    data_plot = moc
    data_plot[data_plot < clevel[0]] = clevel[0] + np.finfo(np.float32).eps
    data_plot[data_plot > clevel[-1]] = clevel[-1] - np.finfo(np.float32).eps
    hp1 = plt.contourf(lat,
                       depth,
                       data_plot,
                       levels=clevel,
                       extend='both',
                       cmap=cmap0)
    CS = plt.contour(lat,
                     depth,
                     data_plot,
                     levels=clevel,
                     colors='k',
                     linewidths=[0.5, 0.25],
                     antialised=True)
    if do_clabel:
        ax1.clabel(CS,
                   CS.levels[np.where(CS.levels != cref)],
                   inline=1,
                   inline_spacing=1,
                   fontsize=6,
                   fmt='%1.1f Sv')
    if len(bottom) > 0:
        ax1.plot(lat, bottom, color='k')
        ax1.fill_between(lat, bottom, depth[-1], color=cbot,
                         zorder=2)  #,alpha=0.95)

    #___________________________________________________________________________
    for im in ax1.get_images():
        im.set_clim(clevel[0], clevel[-1])
    #___________________________________________________________________________
    ax1.text(txtx,
             txty,
             str_descript,
             fontsize=14,
             fontweight='bold',
             horizontalalignment='left')
    ax1.grid(color='k', linestyle='-', linewidth=0.25, alpha=1.0)
    ax1.set_xlabel('Latitudes [deg]', fontsize=12)
    ax1.set_ylabel('Depth [m]', fontsize=12)

    #+_________________________________________________________________________+
    #| plot first colorbar                                                     |
    #+_________________________________________________________________________+
    cbar1 = plt.colorbar(hp1,
                         ax=ax1,
                         ticks=clevel,
                         drawedges=True,
                         extend='neither',
                         extendrect=False,
                         extendfrac='auto')
    cbar1.set_label('Global Meridional Overturning Circulation [Sv]' + '\n' +
                    str_time,
                    size=fsize + 2)
    if which_moc == 'gmoc':
        cbar1.set_label('Global Meridional Overturning Circulation [Sv]' +
                        '\n' + str_time,
                        size=fsize + 2)
    elif which_moc == 'amoc' or which_moc == 'amoc2':
        cbar1.set_label('Atlantic Meridional Overturning Circulation [Sv]' +
                        '\n' + str_time,
                        size=fsize + 2)
    elif which_moc == 'pmoc':
        cbar1.set_label(
            'Indo-Pacific Meridional Overturning Circulation [Sv]' + '\n' +
            str_time,
            size=fsize + 2)
    elif which_moc == 'imoc':
        cbar1.set_label('Indo Meridional Overturning Circulation [Sv]' + '\n' +
                        str_time,
                        size=fsize + 2)

    ncbar_l = len(cbar1.ax.get_yticklabels()[:])
    idx_cref = np.where(clevel == cref)[0]
    idx_cref = np.asscalar(idx_cref)
    nmax_cbar_l = 10
    nstep = ncbar_l / nmax_cbar_l
    nstep = np.int(np.floor(nstep))
    if nstep == 0: nstep = 1
    plt.setp(cbar1.ax.get_yticklabels()[:], visible=False)
    plt.setp(cbar1.ax.get_yticklabels()[idx_cref::nstep], visible=True)
    plt.setp(cbar1.ax.get_yticklabels()[idx_cref::-nstep], visible=True)
    plt.show(block=False)

    fig.canvas.draw()
    return (fig, ax1)
Exemplo n.º 3
0
def plot_map_clima_panel_matrix(inputarray, mesh, var_rows, var_columns, which_var, \
    whatisrow='depth', whatiscolumn='descript/path',\
    which_year=[1989,2009], which_mon=list(range(1,12+1)), which_dep=np.arange(0,250+1,10), \
    which_woa='woa2018', do_rmse=True, fsize=10, do_enumerate=True):

    nr, nc = len(var_rows), len(var_columns)
    
    #___________________________________________________________________________
    data1 = fesom_data(inputarray) # init fesom2.0 data object
    data1.var, data1.year, data1.month, data1.depth =  which_var, which_year, which_mon, which_dep

    #___________________________________________________________________________
    if data1.var=='temp' : cmin1,cmax1,cref1,cnumb1  = -4.0, 4.0, 0.0, 20 # [cmin, cmax, cref] --> salt+ 
    if data1.var=='salt' : cmin1,cmax1,cref1,cnumb1  = -0.5, 0.5, 0.0, 20 # [cmin, cmax, cref] --> salt
    cmap1,clevel1= colormap_c2c(cmin1,cmax1,cref1,cnumb1,'blue2red')
    do_drawedges=True

    #___________________________________________________________________________
    # LOAD WOA CLIMATOLOGY
    if which_woa=='woa2005': clim_descr, clim_path, clim_fname  = 'WOA05', '../view/woa2005/', 'woa2005TS.nc'
    if which_woa=='woa2018': clim_descr, clim_path, clim_fname  = 'WOA18', '/work/ollie/pscholz/INIT_HYDRO/woa2018/', 'woa2018TS_0.25deg.nc'
    clim  = clim_data(clim_path,clim_fname,data1.var)
    clim.descript = data1.descript+'-'+clim_descr
    clim.crange,clim.cmap, clim.cnumb      = data1.crange,data1.cmap, data1.cnumb
    clim.str_time, clim.str_dep            = data1.str_time, data1.str_dep
    clim.sname, clim.lname, clim.unit      = data1.sname, data1.lname, data1.unit
    clim.proj, clim.proj_lon, clim.proj_lat= data1.proj, data1.proj_lon, data1.proj_lat

    #___________________________________________________________________________
    # setup figures and axes
    if   nc!=1 and nr!=1: fig, ax = plt.subplots(nrows=nr, ncols=nc, figsize=[4*nc,3*nr])
    elif nc==1          : fig, ax = plt.subplots(nrows=nr, ncols=nc, figsize=[8*nc,4*nr])
    elif nr==1          : fig, ax = plt.subplots(nrows=nr, ncols=nc, figsize=[4*nc,8*nr])
    plt.subplots_adjust(bottom=0.05, top=0.95, left=0.05, right=0.95,wspace=0.01, hspace=0.01)

    #___________________________________________________________________________
    # start row/column loop
    print(' --> total nr. of matrix panels: {:d} |'.format(nr*nc), end='')
    ni = 0
    for nri in range(0,nr):
        for nci in range(0,nc):
            ni = ni+1
            print('{:d}|'.format(ni), end='')
            #___________________________________________________________________
            # if subplot should be left empty
            if not var_columns[nci]: 
                ax[nri,nci].remove()
                continue
            
            #___________________________________________________________________
            # set row/column specific info
            if   whatisrow    =='depth':
                data1.depth = var_rows[nri]
            elif whatiscolumn =='depth':
                data1.depth = var_columns[nri]
            else: 
                print(' --> ERROR: this panel matrix configuration is not supported')
                exit
            
            if   whatisrow    =='descript/path':
                 data1.descript, data1.path = var_rows[nci][0],var_rows[nci][1]
            elif whatiscolumn =='descript/path':
                data1.descript, data1.path = var_columns[nci][0],var_columns[nci][1]
            else: 
                print(' --> ERROR: this panel matrix configuration is not supported')
                exit
            
            #___________________________________________________________________
            # load data
            fesom_load_data_horiz_netcdf4(mesh,data1,do_output=False)
            data11 = clim_data_anom(mesh,clim,data1,clim_descr)
            
            #___________________________________________________________________
            # compute RMSE
            meanbias1 = np.nansum(np.abs(data11.anom))/np.isnan(data11.anom).sum()
            
            #___________________________________________________________________
            # do axis writtings
            xl, yl, str_tl, str_yl, str_xl = [], [], [], [], []
            if nri == nr-1      : xl = [0,0,0,1]
            if nci == 0         : yl = [1,0,0,0]
            
            if  whatisrow =='depth':
                if nci == 0: str_yl=data11.str_dep[7::]+'\n\n'  
            elif whatisrow =='descript/path':
                if nci == 0: str_yl=data11.descript+'\n\n'  
                    
            if whatiscolumn =='depth':
                if nri == 0: str_tl=data11.str_dep[7::]
            elif whatiscolumn =='descript/path':
                if nri == 0: str_tl=data11.descript
                
            str_err=[]
            if do_rmse:
                if data1.var=='temp': str_err='\n Err={:2.2f}°C'.format(meanbias1)
                if data1.var=='salt': str_err='\n Err={:2.2f}psu'.format(meanbias1)   
            
            #___________________________________________________________________
            # do subplot
            if nc==1 and nr==1:
                dumax,hp = plot_map_clima(fig, ax, mesh, data11, inputarray, clevel1, cmap1, \
                                        xl=xl, yl=yl, str_tl=str_tl, str_yl=str_yl, str_xl=str_xl, \
                                        str_txt=str_err, fsize=fsize )
            
            elif nc!=1 and nr!=1:
                dumax,hp = plot_map_clima(fig, ax[nri,nci], mesh, data11, inputarray, clevel1, cmap1, \
                                        xl=xl, yl=yl, str_tl=str_tl, str_yl=str_yl, str_xl=str_xl, \
                                        str_txt=str_err, fsize=fsize )
            elif nc==1:
                dumax,hp = plot_map_clima(fig, ax[nri], mesh, data11, inputarray, clevel1, cmap1, \
                                        xl=xl, yl=yl, str_tl=str_tl, str_yl=str_yl, str_xl=str_xl, \
                                        str_txt=str_err, fsize=fsize )
            elif nr==1:
                dumax,hp = plot_map_clima(fig, ax[nci], mesh, data11, inputarray, clevel1, cmap1, \
                                        xl=xl, yl=yl, str_tl=str_tl, str_yl=str_yl, str_xl=str_xl, \
                                        str_txt=str_err, fsize=fsize )
            
            #___________________________________________________________________
            # enumerate a, b, c, ....
            fac = 2.5
            if do_enumerate:
                txtx, txty = inputarray['which_box'][0]+fac,inputarray['which_box'][3]-fac
                if nc*nr>26 : str_enum = chr(ord('`')+nci+1)+str(nri+1)+')'
                else        : str_enum = chr(ord('`')+ni)+')'
                if nc==1 and nr==1:
                    ax.text(txtx,txty,str_enum, \
                                    fontweight='normal',horizontalalignment='left',\
                                    verticalalignment='top',fontsize=fsize)
                elif nc!=1 and nr!=1:
                    ax[nri,nci].text(txtx,txty,str_enum, \
                                    fontweight='normal',horizontalalignment='left',\
                                    verticalalignment='top',fontsize=fsize)
                elif nc==1:
                    ax[nri].text(txtx,txty,str_enum, \
                                    fontweight='normal',horizontalalignment='left',\
                                    verticalalignment='top',fontsize=fsize)
                elif nr==1:
                    ax[nci].text(txtx,txty,str_enum, \
                                    fontweight='normal',horizontalalignment='left',\
                                    verticalalignment='top',fontsize=fsize)
    #___________________________________________________________________________
    # do colorbar
    str_unit = data1.unit
    if data1.var=='temp': str_unit = '[°C]'
    cbar1 = setup_colorbar(hp, ax, clevel1, cref1, data1.lname+' anomaly '+' '+str_unit+'\n '+data1.str_time, ncl=10, orientation='vertical')

    #___________________________________________________________________________
    # adapt panel and colorbar positions
    fig.canvas.draw()
    pos_cbar1 = cbar1.ax.get_position()
    if   nc==1 and nr==1: pos_ax    = ax.get_position()
    elif nc!=1 and nr!=1: pos_ax    = ax[0,0].get_position()
    else              : pos_ax    = ax[0].get_position()

    x0,y0  = 0.1, 0.1
    #xg, yg = 0.005, 0.005
    xg, yg = 0.01, 0.01
    w, h   = pos_ax.width, pos_ax.height

    fac    = 0.70/(w*nc+xg*(nc-1))
    w, h   = w*fac, h*fac

    print(w,h)
    for nri in range(0,nr):
        for nci in range(0,nc):
            if   nc==1 and nr==1: ax.set_position( [x0+(w+xg)*nci, y0+(h+yg)*(nr-nri-1), w, h])
            elif nc!=1 and nr!=1: ax[nri,nci].set_position( [x0+(w+xg)*nci, y0+(h+yg)*(nr-nri-1), w, h])
            elif nc==1          : ax[nri].set_position(     [x0+(w+xg)*nci, y0+(h+yg)*(nr-nri-1), w, h])
            elif nr==1          : ax[nci].set_position(     [x0+(w+xg)*nci, y0+(h+yg)*(nr-nri-1), w, h])
    cbar1.ax.set_position([x0+(w+xg)*nc, y0, pos_cbar1.width, nr*h+(nr-1)*yg])
    #cbar1.ax.set_aspect(1/(pos_cbar1.width/(nr*h+(nr-1)*yg)/20*4))
    cbar1.ax.set_aspect(1/(pos_cbar1.width/(nr*h+(nr-1)*yg)/20*4*(5-(nr-1))))
    fig.canvas.draw()        
    
    #___________________________________________________________________________
    # return value
    return(data11)