def make_plot():
    bbox = [-82, -80, 24, 26]
    projection = ccrs.PlateCarree()

    fig, ax = plt.subplots(figsize=(9, 9), subplot_kw=dict(projection=projection))

    ax.set_extent(bbox)

    land = cfeature.NaturalEarthFeature(
        "physical", "land", "10m", edgecolor="face", facecolor=[0.85] * 3
    )

    ax.add_feature(land, zorder=0)
    ax.coastlines("10m", zorder=1)

    ax.set_xticks(np.linspace(bbox[0], bbox[1], 3), crs=projection)
    ax.set_yticks(np.linspace(bbox[2], bbox[3], 3), crs=projection)
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    return fig, ax
def PlotStdTest(t, F, lat_observ, lon_observ, title, filename):
	theta = np.linspace(0, 2 * np.pi, 100)
	center, radius = [0.5, 0.5], 0.5
	verts = np.vstack([np.sin(theta), np.cos(theta)]).T
	circle = mpath.Path(verts * radius + center)
	proj = ccrs.Stereographic(central_longitude=-60, central_latitude=-90)
	xticks = [-180, -90, 0, 90, 180]
	yticks = [-90, -65, -40, -15, 0]
	month = ['September', 'October', 'November', 'December', 'January', 'February']
	clevs = np.arange(0, 3.5, 0.5)
	barra = plt.cm.get_cmap('YlOrRd')
	#norm = col
	barra.set_over(barra(barra.N-1))
	fig = plt.figure(1,(8, 5.7), 300)
	for i in np.arange(6):
		ax =plt.subplot(2, 3, i + 1, projection=proj)
		ax.set_extent([0, 359, -90, 0], crs=ccrs.PlateCarree()) #set map limits
		gl = ax.gridlines(xlocs=xticks, ylocs=yticks, draw_labels=False, 
				 crs=ccrs.PlateCarree(), color='black', alpha=0.6,
				 linewidth=0.3, linestyle='--')
		gl.n_steps = 90	
		ax.set_boundary(circle, transform=ax.transAxes)
		ax.coastlines()
		im = ax.contourf(lon_observ, lat_observ, F[i + 1, :, :], clevs,
				transform=ccrs.PlateCarree(), cmap=barra, extend='max', origin='lower')#,
#				vmin=clevs[0], vmax=clevs[-1])
		lon_formatter = LongitudeFormatter(zero_direction_label=True)
		lat_formatter = LatitudeFormatter()
		ax.xaxis.set_major_formatter(lon_formatter)
		ax.yaxis.set_major_formatter(lat_formatter)
		plt.title(month[i], fontsize=10)
	plt.suptitle(title, fontsize=12, x=0.52, y=0.9)
	fig.subplots_adjust(bottom=0.17, top=0.82, hspace=0.2, wspace=0.05)
	cbar_ax = fig.add_axes([0.3, 0.1, 0.4, 0.05])
	fig.colorbar(im, cax=cbar_ax, orientation='horizontal')
	plt.savefig(filename, dpi=300, bbox_inches='tight')
	plt.clf()
	plt.cla()
	plt.close()
Пример #3
0
def set_grid(ax, lat=[29, 32.5], lon=[87, 93], span=1.):
    '''
    魔改matplotlib添加经纬度坐标

    Parameters
    ----------
    lat, lon: 经纬度范围
    '''
    from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

    ### 限定区域
    extent = [np.min(lon), np.max(lon), np.min(lat), np.max(lat)]
    ax.set_extent(extent, crs=ccrs.PlateCarree())

    lat_span = span  # 经纬度间隔
    lon_span = span
    ax.set_xticks(np.arange(lon[0], lon[1] + lon_span, lon_span))
    ax.set_yticks(np.arange(lat[0], lat[1] + lat_span, lat_span))
    ax.tick_params(top=True, bottom=True, left=True, right=True)

    ### 取消坐标单位度°的小圆点
    lon_formatter = LongitudeFormatter(degree_symbol='')
    lat_formatter = LatitudeFormatter(degree_symbol='')
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.tick_params(axis='both', labelsize=12, direction='out')

    # ### 国界线
    # linewidth = 1
    # # ax.add_feature(cfeature.BORDERS.with_scale('10m'), lw=linewidth) # 藏南被吃了,慎用
    # f_in = '/home/zzhzhao/code/shpfiles/boundary/bou1_4m/bou1_4l.shp'
    # shp = geopandas.read_file(f_in, encoding='gbk')
    # ax.add_geometries(shp.geometry, crs=ccrs.PlateCarree(), edgecolor='k', alpha=0.4, facecolor='none', lw=linewidth)

    # ### 海岸线
    # ax.coastlines(resolution='10m', lw=linewidth)

    ### 青藏高原
    add_TP(ax, linewidth=1)
Пример #4
0
def format_latlon(
        ax,
        proj,
        latlon_bnds=(-180, 180, -90, 90),
        lon_step=20,
        lat_step=10,
        nformat="g",
):
    """
    Format geoaxes nicely
    """
    (ilon, flon, ilat, flat) = latlon_bnds

    lon_formatter = LongitudeFormatter(number_format=nformat)
    lat_formatter = LatitudeFormatter(number_format=nformat)

    ax.set_xticks(np.arange(ilon, flon, lon_step), crs=proj)
    ax.set_yticks(np.arange(ilat, flat, lat_step), crs=proj)

    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    return ax
Пример #5
0
def plot_panel(n, fig, proj, var, var_num_years, region, title):

    ax = fig.add_axes(panel[n], projection=proj)
    ax.set_extent(plot_info[region][0], ccrs.PlateCarree())

    clevs = np.arange(0, 15.1, 1)
    clevs = plot_info[region][4]
    p1 = ax.contourf(
        var.getLongitude(),
        var.getLatitude(),
        var / var_num_years,
        transform=ccrs.PlateCarree(),
        levels=clevs,
        extend="both",
        cmap="jet",
    )
    ax.coastlines(lw=0.3)
    ax.add_feature(cfeature.LAND, zorder=100, edgecolor="k")

    if title != "Observation":
        ax.set_title("{}".format(title), fontdict=plotTitle)
    else:
        ax.set_title("{}".format(plot_info[region][5]), fontdict=plotTitle)
    ax.set_xticks(plot_info[region][1], crs=ccrs.PlateCarree())
    ax.set_yticks(plot_info[region][2], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True,
                                       number_format=".0f")
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.tick_params(labelsize=8.0, direction="out", width=1)
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    cbax = fig.add_axes(
        (panel[n][0] + 0.6635, panel[n][1] + 0.0215, 0.0326, 0.1792))
    cbar = fig.colorbar(p1, cax=cbax)

    cbar.ax.tick_params(labelsize=9.0, length=0)
    return
Пример #6
0
def draw_map_cartopy(data_name,varname,vmin,vmax,inc,titlestr,s1,s2,sub_no,cmap='RdBu',hatch='/',draw_par=1):
    ds1           =     xr.open_dataset(data_name)
    data          =     ds1[varname].values
    lon           =     ds1.lon
    lat           =     ds1.lat

    axiom = plt.subplot(s1,s2,sub_no,projection=ccrs.PlateCarree(central_longitude=180.0))
    v         =    np.arange(vmin,vmax+inc,inc)

    cs=axiom.contourf(lon, lat, data[0,:,:],v, cmap=cmap,extend='both',transform = ccrs.PlateCarree())
    axiom.coastlines()
    if draw_par:
        axiom.gridlines()

    cbar =  plt.colorbar(cs, shrink=0.5, orientation='horizontal',extend='both')
    axiom.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
    axiom.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    axiom.xaxis.set_major_formatter(lon_formatter)
    axiom.yaxis.set_major_formatter(lat_formatter)
    axiom.set_title(titlestr)
def plot_map(ds, title, kwargs, filename=None):
    proj = ccrs.PlateCarree(central_longitude=0)
    fig, ax = plt.subplots(subplot_kw={'projection': proj})

    ds['difference'].plot.pcolormesh(
        ax=ax,
        transform=ccrs.PlateCarree(),
        cbar_kwargs={
            'orientation': 'horizontal',
            'pad': .1,
            'label': ''
        },
        kwargs={'zorder': 100},
        **kwargs,
    )

    ax.coastlines()
    # ax.add_feature(cartopy.feature.BORDERS)

    longitude_formatter = LongitudeFormatter()
    latitude_formatter = LatitudeFormatter()

    # ax.set_xticks(np.arange(np.floor(da['lon'].min()), da['lon'].max(), 10), crs=proj)
    # ax.set_yticks(np.arange(np.floor(da['lat'].min()), da['lat'].max(), 10), crs=proj)
    #ax.set_xticks(np.arange(-10, 50, 20))
    #ax.set_yticks(np.arange(30, 80, 15))
    ax.set_xlim(-12, 48)
    ax.set_ylim(26, 76)
    #ax.xaxis.set_ticks_position('both')
    #ax.yaxis.set_ticks_position('both')
    ax.xaxis.set_major_formatter(longitude_formatter)
    ax.yaxis.set_major_formatter(latitude_formatter)
    ax.set_xlabel('')
    ax.set_ylabel('')
    # ax.grid(True, zorder=-1)
    ax.set_title(title)

    hatching(ax, ds['lat'], ds['lon'], ds['significant'], force=True)
Пример #8
0
def plot_helper(data):
    projection = ccrs.PlateCarree(central_longitude=180)
    axes_class = (GeoAxes, dict(map_projection=projection))
    lonmin, lonmax = -60, 100
    latmin, latmax = -40, 40
    extent = [latmin, latmax, lonmin, lonmax]
    lons, lats = grid_position(shape=data.shape, extent=extent)

    fig = plt.figure()
    axgr = AxesGrid(fig,
                    111,
                    axes_class=axes_class,
                    nrows_ncols=(3, 2),
                    axes_pad=0.6,
                    cbar_location='right',
                    cbar_mode='single',
                    cbar_pad=0.2,
                    cbar_size='3%',
                    label_mode='')  # note the empty label_mode

    for i, ax in enumerate(axgr):
        ax.coastlines()
        ax.set_xticks(np.linspace(lonmin, lonmax, 5), crs=projection)
        ax.set_yticks(np.linspace(latmin, latmax, 5), crs=projection)
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)

        p = ax.contourf(lons,
                        lats,
                        data[i, ...],
                        transform=projection,
                        cmap='RdYlBu_r')

    axgr.cbar_axes[0].colorbar(p)

    plt.show()
Пример #9
0
def set_lat_lon(ax, xtickrange, ytickrange, label=False, pad=0.05, fontsize=8):
    lon_formatter = LongitudeFormatter(zero_direction_label=True,
                                       degree_symbol='')
    lat_formatter = LatitudeFormatter(degree_symbol='')
    ax.set_yticks(ytickrange, crs=ccrs.PlateCarree())
    ax.set_xticks(xtickrange, crs=ccrs.PlateCarree())
    if label:
        ax.set_xticklabels(xtickrange, fontsize=fontsize)
        ax.set_yticklabels(ytickrange, fontsize=fontsize)
        ax.tick_params(axis='x',
                       which='both',
                       direction='out',
                       bottom=True,
                       top=False,
                       labeltop=False,
                       labelbottom=True,
                       pad=pad)
        ax.tick_params(axis='y', which='both', direction='out', pad=pad)

    else:
        ax.tick_params(axis='x',
                       which='both',
                       direction='out',
                       bottom=True,
                       top=False,
                       labeltop=False,
                       labelleft=False,
                       labelbottom=False)
        ax.tick_params(axis='y',
                       which='both',
                       direction='out',
                       left=True,
                       labelleft=False)

    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.set_ylabel('')
    ax.set_xlabel('')
Пример #10
0
def plt_WndVector(X,Y,U,V,timestr):
	fig = plt.figure()
	ax = plt.subplot(1,1,1,projection=ccrs.PlateCarree())

	Map.readshapefile(os.path.join(shpDir,'bou2_4p'), name='whatever', drawbounds=True,
	                linewidth=0.5, color='black')
	M = np.hypot(U,V)
	#ax.quiver(X, Y, U, V, M, transform=vector_crs, regrid_shape=30)
	Q = ax.quiver(X, Y, U, V, units='x', pivot='tip', color='b', width=0.016,
	    scale=2 / 0.15)
	qk = ax.quiverkey(Q, 0.86, 0.92, 2, r'$4 \frac{m}{s}$', labelpos='E',
	    coordinates='figure')

	# 标注坐标轴
	ax.set_xticks([106, 108, 110, 112], crs=ccrs.PlateCarree())
	ax.set_yticks([21, 23, 25, 27], crs=ccrs.PlateCarree())
	# zero_direction_label用来设置经度的0度加不加E和W
	lon_formatter = LongitudeFormatter(zero_direction_label=False)
	lat_formatter = LatitudeFormatter()
	ax.xaxis.set_major_formatter(lon_formatter)
	ax.yaxis.set_major_formatter(lat_formatter)

	axm = plt.gca()
	xlim, ylim = axm.get_xlim(), axm.get_ylim()
	fcstdates = timestr[:8]+'_'+timestr[8:10]
	hours = timestr[-3:]
	if int(hours) < 100: hours = hours[1:]
	plt.text(xlim[0]+(xlim[1]-xlim[0])*0.25, ylim[1]+(ylim[1]-ylim[0])*0.08,
	    u'广 西 全 区 未 来 '+hours+u' 小 时 10m 风 场 预 报', fontproperties=MYFONT_TITLE)
	plt.text(xlim[0]+(xlim[1]-xlim[0])*0.02, ylim[1]+(ylim[1]-ylim[0])*0.02,
	    u'起 报 时 间 :'+fcstdates, fontproperties=MYFONT)

	# plt.show()
	flename = timestr + '_' + 'WindVector.png'
	OutFigPath = os.path.join(OutFigDir,fcstdates)
	plt.savefig(OutFigPath+'/'+flename, bbox_inches='tight', pad_inches=0.3, dpi=300)
	plt.clf()
        plt.close(fig)
Пример #11
0
def add_gridlines(axs):
    '''Add coastlines and gridlines, showing lat-lon values.
    Requires: import cartopy.feature as cfeature,
            from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    '''
    gls = axs.gridlines(draw_labels=False)
    # Set cartopy Gridliner properties
    gls.ylines = False
    gls.xlines = False
    # Add ticks at labels
    axs.set_xticks(
        gls.xlocator.tick_values(axs.get_extent()[0],
                                 axs.get_extent()[1])[1:-1])
    axs.set_yticks(
        gls.ylocator.tick_values(axs.get_extent()[2],
                                 axs.get_extent()[3])[1:-1])
    axs.xaxis.set_major_formatter(LongitudeFormatter())
    axs.yaxis.set_major_formatter(LatitudeFormatter())
    axs.tick_params(axis="both",
                    direction="in",
                    labelsize=8,
                    top=True,
                    right=True)
Пример #12
0
def make_figure(bbox):
    fig = plt.figure(figsize=figsize)
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())

    # Set extent
    ax.set_extent(bbox)

    # Add filled coastline
    ax.add_feature(cfeature.LAND, facecolor='k', zorder=10)

    # Add Gridlines
    gl = ax.gridlines(draw_labels=True,
                      linewidth=0.75,
                      color='gray',
                      linestyle=':')

    gl.top_labels = gl.right_labels = False
    gl.xformatter = LongitudeFormatter(degree_symbol='')
    gl.yformatter = LatitudeFormatter(degree_symbol='')
    gl.xlabel_style = {'size': 8}
    gl.ylabel_style = {'size': 8}

    return fig, ax
Пример #13
0
def makeMap(maptime=dt.datetime.now(),
            figsize=(10, 4),
            projection=ccrs.PlateCarree(),
            extent=[-165.0, 145.0, 30.0, 80.0],
            nightshade=True):
    #PlateCarree is an equirectangular projection where lines of equal longitude
    #are vertical and lines of equal latitude are horizontal. Spacing between lats
    #and longs are also equal.
    fig = plt.figure(figsize=figsize)
    ax = plt.axes(projection=projection)
    ax.coastlines(color='darkgrey')
    ax.add_feature(cfea.BORDERS, linestyle=':', edgecolor='darkgrey')
    if nightshade:
        ax.add_feature(night.Nightshade(maptime, alpha=0.3))
    lon_formatter = LongitudeFormatter(number_format='.1f',
                                       degree_symbol='',
                                       dateline_direction_label=True)
    lat_formatter = LatitudeFormatter(number_format='.1f', degree_symbol='')
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.set_extent(extent, crs=ccrs.PlateCarree())

    return fig, ax
def dif_clim_tri(obs,mod,latitud,longitud,model,trimestre):
    '''función para calcular la diferencia de climatologías trimestrales'''
    # graficamos la diferencia de las climatologias trimestrales
    dif_clim = mod - obs
    plt.figure()
    clevs = [-6,-5,-4,-3,-2,-1, 0,1,2,3,4,5,6]
    ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=-56))
    fill = ax.contourf(np.real(longitud), np.real(latitud), np.real(dif_clim), np.real(clevs), transform=ccrs.PlateCarree(), cmap=plt.cm.coolwarm, extend='both')
    ax.coastlines()
    #ax.gridlines()
    ax.add_feature(cfeat.RIVERS)
    ax.add_feature(cfeat.BORDERS)
    ax.set_extent([min(longitud), max(longitud), max(latitud), min(latitud)], crs=ccrs.PlateCarree())
    ax.set_xticks([295, 300, 305, 310], crs=ccrs.PlateCarree())
    ax.set_yticks([-25, -30, -35], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True,
                                       number_format='.0f')
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    plt.title(trimestre +' ('+model+' - CRU)')
    plt.colorbar(fill, orientation='horizontal')
    plt.savefig('/home/meteo/investigacion/WR.slp/proyecciones/'+model+'/temp/dif_clim_'+trimestre+'.png', dpi=300)
Пример #15
0
def ecm_tile_sum(ax, var1, var2, vlims, tstep, levels, colors, fmt='%0.5f'):
    ter_lat = 38.7216
    ter_lon = -27.2206
    gra_lat = 39.0525
    gra_lon = -28.0069
    pc = var1[tstep].sum(dim=('z',)).plot.pcolormesh(ax=ax,
                                                transform=ccrs.PlateCarree(),
                                                x='lon', y='lat', vmin=vlims[0],
                                                    vmax=vlims[1])

    cs = var2[tstep].sum(dim=('z',)).plot.contour(ax=ax,
                                                  transform=ccrs.PlateCarree(),
                                                  x='lon', y='lat', levels=levels,
                                                 colors=colors)
    plt.clabel(cs, inline=1, fontsize=10, fmt=fmt)
    ax.set_xticks([-23, -24, -26, -28 ], crs=ccrs.PlateCarree())
    ax.set_yticks([37,39,41], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)

    ax.plot([ter_lon, gra_lon], [ter_lat, gra_lat],
           'ro', transform=ccrs.PlateCarree())

    ax.text(ter_lon+.2, ter_lat+.2,
            'Tericia', transform=ccrs.PlateCarree(), fontsize = 16)

    ax.text(gra_lon+.2, gra_lat+.2,
            'Graciosa', transform=ccrs.PlateCarree(), fontsize = 16)


    coast = cfeature.NaturalEarthFeature(category='physical', scale='10m',
                                    facecolor='none', name='coastline')

    _ = ax.add_feature(coast, edgecolor='black')
    return pc, cs
Пример #16
0
def plot_ts_map(data, title, plotfilename, lats_to_plot, lons_to_plot, colorbar_ticks, colorbar_levels,
                colormap, model_name,xticks, yticks,
                VerboseFlag = False):

    """function to plot one time step of a cube for aerocom"""

    plot = iplt.pcolormesh(data, cmap=colormap, vmin=0., vmax=max(colorbar_levels))
    plot.axes.set_aspect(1.8)
    plot.axes.axis([lats_to_plot.min(), lats_to_plot.max(), lons_to_plot.min(), lons_to_plot.max()])
    # axis = plt.axis([LatsToPlot.min(), LatsToPlot.max(), LonsToPlot.min(), LonsToPlot.max()])
    ax = plot.axes
    annotate_aerocom(ax)
    ax.annotate(model_name, xy=(-174., -83.), xycoords='data', horizontalalignment='left', fontsize=13,
                color='black', bbox=dict(boxstyle='square', facecolor='white', edgecolor='none', alpha=0.7))

    # plt.ylabel(_title(plot_defn.coords[0], with_units=True))
    # plot_defn = iplt._get_plot_defn(cube, mode, ndims)

    plt.colorbar(spacing='uniform', ticks=colorbar_ticks, boundaries=colorbar_levels, extend='max')

    ax.coastlines()
    ax.set_xticks(xticks, crs=ccrs.PlateCarree())
    ax.set_yticks(yticks, crs=ccrs.PlateCarree())
    # ax.set_xticks([-180., -120., -60., 0., 60, 120, 180], crs=ccrs.PlateCarree())
    # ax.set_yticks([-90., -60, -30, 0., 30, 60, 90], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(number_format='.1f', degree_symbol='')
    lat_formatter = LatitudeFormatter(number_format='.1f', degree_symbol='')
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)

    plot.axes.set_title(title)
    plot.axes.set_xlabel('longitude')
    plot.axes.set_ylabel('latitude')
    plt.savefig(plotfilename, dpi=300)
    #pdb.set_trace()
    plt.close()
Пример #17
0
def main():
    projection = ccrs.PlateCarree()
    axes_class = (GeoAxes, dict(map_projection=projection))

    lons, lats, times, data = sample_data_3d((6, 73, 145))

    fig = plt.figure()
    axgr = AxesGrid(fig,
                    111,
                    axes_class=axes_class,
                    nrows_ncols=(3, 2),
                    axes_pad=0.6,
                    cbar_location='right',
                    cbar_mode='single',
                    cbar_pad=0.2,
                    cbar_size='3%',
                    label_mode='')  # note the empty label_mode

    for i, ax in enumerate(axgr):
        ax.coastlines()
        ax.set_xticks(np.linspace(-180, 180, 5), crs=projection)
        ax.set_yticks(np.linspace(-90, 90, 5), crs=projection)
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)

        p = ax.contourf(lons,
                        lats,
                        data[i, ...],
                        transform=projection,
                        cmap='RdBu')

    axgr.cbar_axes[0].colorbar(p)

    plt.show()
Пример #18
0
    def draw_beautiful_map(self):
        '''
        Метод для отрисовки карты
        Используется ортографическая проекция с сцентром в точке центроида шейпа (списка шейпов)
        :return:
        '''
        import numpy as np
        from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
        import glob

        print("Drawing")
        # Grafico
        fig = plt.figure(figsize=(10, 4))
        ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
        print('берега')
        ax.coastlines()
        print('глобал')
        ax.set_global()
        print('countour')
        #ct = ax.contourf(self.var_to_analyze, transform=ccrs.PlateCarree(), cmap="bwr")
        #ct = ax.plot(self.var_to_analyze, transform=ccrs.PlateCarree(), cmap="bwr")
        ct = ax.pcolormesh(self.var_to_analyze,
                           transform=ccrs.PlateCarree(),
                           cmap="bwr")
        ax.gridlines()
        print('color')
        cb = plt.colorbar(ct, orientation="vertical", extendrect='True')
        cb.set_label("Temperatura [°C]")
        print('прочая срань')
        ax.set_xticks(np.arange(-180, 181, 60), crs=ccrs.PlateCarree())
        ax.set_yticks(np.arange(-90, 91, 30), crs=ccrs.PlateCarree())
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
        plt.show()
def graf_clim(clim, lati, long, model, mes):
    '''función para graficar las climatologías de cada mes'''
    plt.figure()
    meses = [
        'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio',
        'agosto', 'setiembre', 'octubre', 'noviembre', 'diciembre'
    ]
    clevs = [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
    ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=-56))
    fill = ax.contourf(np.real(long),
                       np.real(lati),
                       np.real(clim),
                       np.real(clevs),
                       transform=ccrs.PlateCarree(),
                       cmap=plt.cm.PuBuGn,
                       extend='both')
    ax.coastlines()
    #ax.gridlines()
    ax.add_feature(cfeat.RIVERS)
    ax.add_feature(cfeat.BORDERS)
    ax.set_extent([min(long), max(long),
                   max(lati), min(lati)],
                  crs=ccrs.PlateCarree())
    ax.set_xticks([295, 300, 305, 310], crs=ccrs.PlateCarree())
    ax.set_yticks([-25, -30, -35], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True,
                                       number_format='.0f')
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    plt.title(model + ' climatología ' + meses[mes])
    plt.colorbar(fill, orientation='horizontal')
    #plt.title('prec mm/día', fontsize=12)
    plt.savefig('/home/meteo/investigacion/WR.slp/proyecciones/' + model +
                '/prec/clim_' + model + '%d.png' % (mes),
                dpi=300)
Пример #20
0
def draw_EOF_and_PC(eof,pc,lon,lat,contribution):
    # draw EOFi
    fig1 = plt.figure(figsize=[5,15],dpi=100)
    ax1 = []
    neof = eof.shape[0]
    for i in range(neof):
        ax1.append(fig1.add_subplot(neof,1,i+1,projection=ccrs.PlateCarree(central_longitude=180)))
        ax1[i].coastlines()
        p = ax1[i].contourf(lon,lat,eof[i,:,:]*10**2,10,transform=ccrs.PlateCarree(),cmap='coolwarm',extend='both')
        cb = plt.colorbar(p,pad=0.02)
        cb.set_label(r"$\times 10^{-2}$",y=1.1,labelpad=-10,rotation=0,fontsize=8)
        ax1[i].set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
        ax1[i].set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax1[i].xaxis.set_major_formatter(lon_formatter)
        ax1[i].yaxis.set_major_formatter(lat_formatter)   
        
        ax1[i].set_title('EOF'+str(i+1), loc='left', fontsize=10)
        ax1[i].set_title('{:.2f}%'.format(contribution[i]*100), loc='right', fontsize=10)
    fig1.savefig('EOF.png')
    # draw PCi
    len_time = pc.shape[1]
    time_list = np.arange(len_time)
    year_list = 1948 + time_list / 12
    fig2, ax2 = plt.subplots(neof,1,sharex='col')
    for i in range(neof):
        pc_pos = np.where(pc[i,:]<0,0,pc[i,:])
        pc_nag = np.where(pc[i,:]>0,0,pc[i,:])
        ax2[i].bar(year_list, pc_pos, width=0.1, color='r')
        ax2[i].bar(year_list, pc_nag, width=0.1, color='b')
        ax2[i].set_title('PC'+str(i+1), loc='left', fontsize=10)
        ax2[i].set_title('{:.2f}%'.format(contribution[i]*100), loc='right', fontsize=10)
        ax2[i].set_xlim([min(year_list), max(year_list)])
    fig2.savefig('PC.png')
    plt.show()
def PlotCompDiff(var, lat, lon, title, filename):
    proj = ccrs.PlateCarree(central_longitude=180)
    fig = plt.figure(1, (10, 3.7), 300)
    ax = plt.subplot(projection=proj)
    clevs = np.arange(-60, 70, 10)
    barra = plt.cm.RdBu_r
    ax.set_extent([0, 359, -90, 20], crs=ccrs.PlateCarree())
    im = ax.contourf(lon,
                     lat,
                     var,
                     clevs,
                     transform=ccrs.PlateCarree(),
                     cmap=barra,
                     extend='both',
                     vmin=-60,
                     vmax=60)
    barra.set_under(barra(0))
    barra.set_over(barra(barra.N - 1))
    ax.coastlines()
    ax.add_feature(cartopy.feature.BORDERS, linestyle='-',
                   alpha=.5)  #countries
    ax.gridlines(crs=proj, linewidth=0.3, linestyle='-')
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    plt.colorbar(im, orientation='horizontal')
    plt.title(title)
    plt.savefig(filename,
                dpi=300,
                bbox_inches='tight',
                orientation='landscape',
                papertype='A4')
    plt.clf()
    plt.cla()
    plt.close()
Пример #22
0
def plot_3D_trend(trends, lons, lats, gs,
                  tick_max, tick_step, yticks):
    """Plot the trends."""

    ax = plt.subplot(gs[0], projection=ccrs.PlateCarree(central_longitude=180.0))
    plt.sca(ax)

    cmap = plt.cm.RdBu_r
    ticks = numpy.arange(-tick_max, tick_max + tick_step, tick_step)
    cf = ax.contourf(lons, lats, trends, transform=ccrs.PlateCarree(),
                     cmap=cmap, levels=ticks, extend='both')

    ax.coastlines()
    ax.set_yticks(yticks, crs=ccrs.PlateCarree())
    ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.set_xlabel('Longitude', fontsize='small')
    ax.set_ylabel('Latitude', fontsize='small')    

    cbar = plt.colorbar(cf)
    cbar.set_label('$Wm^{-2}$')
Пример #23
0
 def __init__(self, plons, plats):
     self.proj = ccrs.PlateCarree(central_longitude=180)
     self.fig, self.ax = plt.subplots(subplot_kw=dict(projection=self.proj),
                                      figsize=(24, 12),
                                      dpi=400)
     self.ax.set_xticks(np.arange(0, 360, 2.5), crs=ccrs.PlateCarree())
     self.ax.set_yticks(np.arange(-90, 90, 2.5), crs=ccrs.PlateCarree())
     lon_formatter = LongitudeFormatter(zero_direction_label=True)
     lat_formatter = LatitudeFormatter()
     self.ax.xaxis.set_major_formatter(lon_formatter)
     self.ax.yaxis.set_major_formatter(lat_formatter)
     self.ax.grid(alpha=0.5, ls="--")
     hq_border = cfeature.NaturalEarthFeature(
         category="cultural",
         name="admin_0_countries",
         scale="10m",
         facecolor="white",  # cfeature.COLORS['land'],
         edgecolor="black",
         linewidth=1.5,
     )
     self.ax.add_feature(hq_border)
     plons = tuple(plon - 180 for plon in plons)
     self.ax.set_extent([*plons, *plats], crs=self.proj)
     self.ax.tick_params(labelsize=15)
Пример #24
0
                      levels = np.linspace(lower_limitation,upper_limitation,51),
                      extend = 'both',
                      projection=ccrs.PlateCarree())
#add colorbar
cb1 = fig.colorbar(contf1, ticks = np.linspace(lower_limitation,upper_limitation,11),  
                   format = '%.0f',
                   orientation = 'horizontal',fraction=0.08, pad=0.15)
#set colorbar format
cb1.set_label('cm/year', fontsize = 16)
cb1.ax.tick_params(labelsize=16)
#set ax1 label's and tick's format
ax1.set_xticks([ -180, -120, -60,0, 60, 120, 180,], crs=ccrs.PlateCarree())
ax1.set_yticks([-90, -60, -30, 0, 30, 60, 90],  crs=ccrs.PlateCarree())
ax1.tick_params(axis='both', labelsize=20)
ax1.xaxis.set_major_formatter(LongitudeFormatter())
ax1.yaxis.set_major_formatter(LatitudeFormatter())

##plot ax2, temporal change of zonal average evaporation
ax2 = fig.add_subplot(grid[0,2])
month = month_list[0]
ax2.plot(qflx_modern_monthly_zonal[0,:], lat, linewidth=3.0, 
         #color = 'b', 
         linestyle = '-', label=f'{month}')
ax2.plot(qflx_modern_annual_zonal, lat, linewidth=2.0, 
         #color = 'b', 
         linestyle = '--', label='Annual')
#set ax2 format
ax2.set_ylabel('°N',fontsize = 16)
ax2.tick_params(labelsize=16) 
ax2.set_xlabel("cm/year",fontsize = 16)
ax2.set_xlim([0,200])
Пример #25
0
#for i in mgex:
#    if i['reciver'] == ReciverType[1]:
#        lists.append(i)

#plot_sites = pd.array(lists)
#plot_sites = pd.array('Site')

# Add MGEX & IGS core sites
ax.plot(mgex['lat'][0:9], mgex['long'][0:9], 'o', color='darkorange',mec='k',mew=0.5, transform=ccrs.Geodetic(), ms=8.0)
ax.plot(mgex['lat'][9:21], mgex['long'][9:21], 'o', color='m',mec='k',mew=0.5, transform=ccrs.Geodetic(), ms=8.0)
ax.plot(mgex['lat'][21:36], mgex['long'][21:36], 'o', color='forestgreen',mec='k',mew=0.5, transform=ccrs.Geodetic(), ms=8.0)
ax.plot(mgex['lat'][36:45], mgex['long'][36:45], 'o', color='royalblue',mec='k', mew=0.5,transform=ccrs.Geodetic(), ms=8.0)

#for j in plot_sites:
#    plt.text(j['long'], j['lat'], j['site'], transform=ccrs.Geodetic(), FontSize=10)

ax.legend(['JAVAD TRE_3','JAVAD TRE_3 DE','SEPT POLARX5','TRIMBLE ALLOY'],loc='lower left',fontsize=8)

# Plot gridlines
# ax.gridlines(linestyle='--', LineWidth=0.05)
ax.set_global()
ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)

fig.savefig('sites1.tiff', bbox_inches='tight', dpi=400)
plt.show()
Пример #26
0
    def __call__(self,
                 da,
                 ax=None,
                 bnds=[0, 360, -90, 90],
                 projection_name='PlateCarree',
                 **plt_kwargs):

        # Central longitude must be between -180 and 180 (greenwich meridian is 0)
        #lon_0 = (bnds[0] + bnds[1])/2 - 360
        lon_0 = (bnds[0] + bnds[1]) / 2

        #print('lon_0', lon_0)

        if projection_name == 'PlateCarree':
            projection = cart.crs.PlateCarree(central_longitude=lon_0)
        elif projection_name == 'Robinson':
            projection = cart.crs.Robinson(central_longitude=lon_0)
        else:
            print('Projection name must be "PlateCarree" or "Robinson".')

        assert set(da.dims) == set(
            ['face', 'j', 'i']), "da must have dimensions ['face', 'j', 'i']"

        if ax is None:
            fig, ax = plt.subplots(figsize=(12, 6))

        #print(self.orig_grid.shape)
        #print(da.values.shape)
        #print(self.new_grid.shape)

        field = pyresample.kd_tree.resample_nearest(self.orig_grid,
                                                    da.values,
                                                    self.new_grid,
                                                    radius_of_influence=100000,
                                                    fill_value=None)

        vmax = plt_kwargs.pop('vmax', field.max())
        vmin = plt_kwargs.pop('vmin', field.min())

        m = plt.axes(projection=projection)
        x, y = self.new_grid_lon, self.new_grid_lat

        #ax= plt.gca()

        pardiff = 30.
        merdiff = 60.

        if np.abs(bnds[1] - bnds[0]) < 180:
            merdiff = 30.
        if np.abs(bnds[1] - bnds[0]) < 90:
            merdiff = 15.
        if np.abs(bnds[3] - bnds[2]) < 90:
            pardiff = 15.

        par = np.arange(-90., 90. + pardiff, pardiff)
        mer = np.arange(-180., 180. + merdiff, merdiff)

        ax = plt.gca()
        ax.set_xticks(mer, crs=cart.crs.PlateCarree())
        ax.set_yticks(par, crs=cart.crs.PlateCarree())
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
        ax.get_yaxis().set_tick_params(direction='out')
        ax.get_xaxis().set_tick_params(direction='out')

        ax.set_extent((bnds[0], bnds[1], bnds[2], bnds[3]),
                      crs=cart.crs.PlateCarree())

        # Find index where data is splitted for mapping
        split_lon_idx = round(x.shape[1] /
                              (360 / (lon_0 if lon_0 > 0 else lon_0 + 360)))

        p = m.pcolormesh(x[:, :split_lon_idx],
                         y[:, :split_lon_idx],
                         field[:, :split_lon_idx],
                         vmax=vmax,
                         vmin=vmin,
                         transform=cart.crs.PlateCarree(),
                         zorder=1,
                         **plt_kwargs)
        p = m.pcolormesh(x[:, split_lon_idx:],
                         y[:, split_lon_idx:],
                         field[:, split_lon_idx:],
                         vmax=vmax,
                         vmin=vmin,
                         transform=cart.crs.PlateCarree(),
                         zorder=2,
                         **plt_kwargs)

        gl = ax.gridlines(crs=cart.crs.PlateCarree(),
                          linewidth=0.5,
                          color='black',
                          alpha=0.6,
                          linestyle='-.',
                          zorder=10)
        gl.xlocator = mticker.FixedLocator(mer)
        gl.ylocator = mticker.FixedLocator(par)

        #ax.set_facecolor('grey')

        #m.add_feature(cart.feature.LAND, facecolor='0.5', zorder=3)
        #m.add_feature(cart.feature.COASTLINE,linewidth=0.5, zorder=15)
        label = ''
        if da.name is not None:
            label = da.name
        if 'units' in da.attrs:
            label += ' [%s]' % da.attrs['units']
        orient = 'vertical'
        if np.abs(bnds[1] - bnds[0]) > (np.abs(bnds[3] - bnds[2]) - 10):
            orient = 'horizontal'
        cb = plt.colorbar(p,
                          fraction=0.07,
                          pad=0.1,
                          label=label,
                          orientation=orient)

        return m, ax
Пример #27
0
    def __init__(self,
                 axes,
                 crs,
                 draw_labels=False,
                 xlocator=None,
                 ylocator=None,
                 collection_kwargs=None,
                 xformatter=None,
                 yformatter=None,
                 dms=False,
                 x_inline=None,
                 y_inline=None,
                 auto_inline=True):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.
        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            longitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format
            latitude labels. It defaults to None, which implies the use of a
            :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection

        .. note:: Note that the "x" and "y" labels for locators and
             formatters do not necessarily correspond to X and Y,
             but to longitudes and latitudes: indeed, according to
             geographical projections, meridians and parallels can
             cross both the X axis and the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, cartopy.crs.PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter or LongitudeFormatter(dms=dms)

        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter or LatitudeFormatter(dms=dms)

        #: Whether to draw labels on the top of the map.
        self.top_labels = draw_labels

        #: Whether to draw labels on the bottom of the map.
        self.bottom_labels = draw_labels

        #: Whether to draw labels on the left hand side of the map.
        self.left_labels = draw_labels

        #: Whether to draw labels on the right hand side of the map.
        self.right_labels = draw_labels

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        #: Whether to draw the longitude gridlines (meridians).
        self.xlines = True

        #: Whether to draw the latitude gridlines (parallels).
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = {}

        #: The padding from the map edge to the x labels in points.
        self.xpadding = 5

        #: The padding from the map edge to the y labels in points.
        self.ypadding = 5

        #: Allow the rotation of labels.
        self.rotate_labels = True

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # Plotted status
        self._plotted = False

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
Пример #28
0
def plot_panel(n,
               fig,
               proj,
               var,
               clevels,
               cmap,
               title,
               parameters,
               stats=None):

    var = add_cyclic(var)
    lon = var.getLongitude()
    lat = var.getLatitude()
    var = ma.squeeze(var.asma())

    # Contour levels
    levels = None
    norm = None
    if len(clevels) > 0:
        levels = [-1.0e8] + clevels + [1.0e8]
        norm = colors.BoundaryNorm(boundaries=levels, ncolors=256)

    # ax.set_global()
    region_str = parameters.regions[0]
    region = regions_specs[region_str]
    global_domain = True
    full_lon = True
    if "domain" in region.keys():  # type: ignore
        # Get domain to plot
        domain = region["domain"]  # type: ignore
        global_domain = False
    else:
        # Assume global domain
        domain = cdutil.region.domain(latitude=(-90.0, 90, "ccb"))
    kargs = domain.components()[0].kargs
    lon_west, lon_east, lat_south, lat_north = (0, 360, -90, 90)
    if "longitude" in kargs:
        full_lon = False
        lon_west, lon_east, _ = kargs["longitude"]
        # Note cartopy Problem with gridlines across the dateline:https://github.com/SciTools/cartopy/issues/821. Region cross dateline is not supported yet.
        if lon_west > 180 and lon_east > 180:
            lon_west = lon_west - 360
            lon_east = lon_east - 360

    if "latitude" in kargs:
        lat_south, lat_north, _ = kargs["latitude"]
    lon_covered = lon_east - lon_west
    lon_step = determine_tick_step(lon_covered)
    xticks = np.arange(lon_west, lon_east, lon_step)
    # Subtract 0.50 to get 0 W to show up on the right side of the plot.
    # If less than 0.50 is subtracted, then 0 W will overlap 0 E on the left side of the plot.
    # If a number is added, then the value won't show up at all.
    if global_domain or full_lon:
        xticks = np.append(xticks, lon_east - 0.50)
        proj = ccrs.PlateCarree(central_longitude=180)
    else:
        xticks = np.append(xticks, lon_east)
    lat_covered = lat_north - lat_south
    lat_step = determine_tick_step(lat_covered)
    yticks = np.arange(lat_south, lat_north, lat_step)
    yticks = np.append(yticks, lat_north)

    # Contour plot
    ax = fig.add_axes(panel[n], projection=proj)
    ax.set_extent([lon_west, lon_east, lat_south, lat_north], crs=proj)
    cmap = get_colormap(cmap, parameters)
    p1 = ax.contourf(
        lon,
        lat,
        var,
        transform=ccrs.PlateCarree(),
        norm=norm,
        levels=levels,
        cmap=cmap,
        extend="both",
    )

    # ax.set_aspect('auto')
    # Full world would be aspect 360/(2*180) = 1
    ax.set_aspect((lon_east - lon_west) / (2 * (lat_north - lat_south)))
    ax.coastlines(lw=0.3)
    if not global_domain and "RRM" in region_str:
        ax.coastlines(resolution="50m", color="black", linewidth=1)
        state_borders = cfeature.NaturalEarthFeature(
            category="cultural",
            name="admin_1_states_provinces_lakes",
            scale="50m",
            facecolor="none",
        )
        ax.add_feature(state_borders, edgecolor="black")
    if title[0] is not None:
        ax.set_title(title[0], loc="left", fontdict=plotSideTitle)
    if title[1] is not None:
        ax.set_title(title[1], fontdict=plotTitle)
    if title[2] is not None:
        ax.set_title(title[2], loc="right", fontdict=plotSideTitle)
    ax.set_xticks(xticks, crs=ccrs.PlateCarree())
    ax.set_yticks(yticks, crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True,
                                       number_format=".0f")
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.tick_params(labelsize=8.0, direction="out", width=1)
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")

    # Color bar
    cbax = fig.add_axes(
        (panel[n][0] + 0.6635, panel[n][1] + 0.0215, 0.0326, 0.1792))
    cbar = fig.colorbar(p1, cax=cbax)
    w, h = get_ax_size(fig, cbax)

    if levels is None:
        cbar.ax.tick_params(labelsize=9.0, length=0)

    else:
        maxval = np.amax(np.absolute(levels[1:-1]))
        if maxval < 10.0:
            fmt = "%5.2f"
            pad = 25
        elif maxval < 100.0:
            fmt = "%5.1f"
            pad = 25
        else:
            fmt = "%6.1f"
            pad = 30
        cbar.set_ticks(levels[1:-1])
        labels = [fmt % level for level in levels[1:-1]]
        cbar.ax.set_yticklabels(labels, ha="right")
        cbar.ax.tick_params(labelsize=9.0, pad=pad, length=0)

    # Min, Mean, Max
    fig.text(
        panel[n][0] + 0.6635,
        panel[n][1] + 0.2107,
        "Max\nMean\nMin",
        ha="left",
        fontdict=plotSideTitle,
    )
    fig.text(
        panel[n][0] + 0.7635,
        panel[n][1] + 0.2107,
        "%.2f\n%.2f\n%.2f" % stats[0:3],
        ha="right",
        fontdict=plotSideTitle,
    )

    # RMSE, CORR
    if len(stats) == 5:
        fig.text(
            panel[n][0] + 0.6635,
            panel[n][1] - 0.0105,
            "RMSE\nCORR",
            ha="left",
            fontdict=plotSideTitle,
        )
        fig.text(
            panel[n][0] + 0.7635,
            panel[n][1] - 0.0105,
            "%.2f\n%.2f" % stats[3:5],
            ha="right",
            fontdict=plotSideTitle,
        )

    # grid resolution info:
    if n == 2 and "RRM" in region_str:
        dlat = lat[2] - lat[1]
        dlon = lon[2] - lon[1]
        fig.text(
            panel[n][0] + 0.4635,
            panel[n][1] - 0.04,
            "Resolution: {:.2f}x{:.2f}".format(dlat, dlon),
            ha="left",
            fontdict=plotSideTitle,
        )
 def gridline_draw(self,
                   grid_linewidth,
                   grid_color,
                   grid_type,
                   big_interval_x,
                   big_interval_y,
                   small_interval_x,
                   small_interval_y,
                   label_size,
                   label_color,
                   l_x,
                   r_x,
                   b_y,
                   t_y,
                   tick_length,
                   xlabel=None,
                   xlabelsize=None):
     '''
     废弃方法
     # 可以控制坐标轴出现的位置,设置False表示隐藏,0表示显示
     if top_labels==0: gl.top_labels = True
     if top_labels==1: gl.top_labels = False
     if bottom_labels==0: gl.bottom_labels = True
     if bottom_labels==1: gl.bottom_labels = False
     if right_labels==0: gl.right_labels = True
     if right_labels==1: gl.right_labels = False
     if left_labels==0: gl.left_labels = True
     if left_labels==1: gl.left_labels = False
     # 自定义给出x轴Locator的位置
     gl.xlocator = mticker.FixedLocator(np.arange(l_x, r_x+big_interval_x, big_interval_x))
     gl.ylocator = mticker.FixedLocator(np.arange(b_y, t_y+big_interval_y, big_interval_y))
     gl.xformatter = LONGITUDE_FORMATTER
     gl.yformatter = LATITUDE_FORMATTER
     gl.xlabel_style = {"color": label_color, "font": Times}
     gl.ylabel_style = {'size': label_size, 'color': label_color, "font": Times}
     '''
     # 绘制网格
     gl = self.axe.gridlines(crs=ccrs.PlateCarree(),
                             draw_labels=True,
                             linewidth=grid_linewidth,
                             color=grid_color,
                             linestyle=grid_type)
     gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
     gl.xlocator = mticker.FixedLocator(
         np.arange(l_x, r_x + big_interval_x, big_interval_x))
     gl.ylocator = mticker.FixedLocator(
         np.arange(b_y, t_y + big_interval_y, big_interval_y))
     self.axe.set_xticks(np.arange(l_x, r_x + big_interval_x / 2,
                                   big_interval_x),
                         crs=ccrs.PlateCarree())
     self.axe.set_yticks(np.arange(b_y, t_y + big_interval_y / 2,
                                   big_interval_y),
                         crs=ccrs.PlateCarree())
     self.axe.xaxis.set_major_formatter(LongitudeFormatter())
     self.axe.yaxis.set_major_formatter(LatitudeFormatter())
     try:
         if xlabel == None:  # 如果ticks不为None,那么就会报错,然后就可以进入下面的设置ticks
             print("xlabel为空")
     except:
         print("xlabel不为空")
         plt.xlabel(xlabel,
                    fontproperties=FontProperties(fname="./font/Times.ttf",
                                                  size=xlabelsize))
     # 下面的用于设置minor刻度,不需要就注释掉
     self.axe.set_xticks(np.arange(l_x, r_x, small_interval_x),
                         crs=ccrs.PlateCarree(),
                         minor=True)
     self.axe.set_yticks(np.arange(b_y, t_y, small_interval_y),
                         crs=ccrs.PlateCarree(),
                         minor=True)
     self.axe.tick_params(labelcolor=label_color, length=tick_length)
     labels = self.axe.get_xticklabels() + self.axe.get_yticklabels()
     [
         label.set_fontproperties(
             FontProperties(fname="./font/Times.ttf", size=label_size))
         for label in labels
     ]
     print("绘制地理网格")
Пример #30
0
def plot_field_map(field_var,
                   lat,
                   lon,
                   levels=50,
                   add_cyclic_point=True,
                   title=None,
                   title_size=20,
                   title_weight='normal',
                   figsize=[10, 8],
                   site_lats=None,
                   site_lons=None,
                   site_marker='o',
                   site_markersize=50,
                   site_color=sns.xkcd_rgb['amber'],
                   projection='Robinson',
                   transform=ccrs.PlateCarree(),
                   proj_args=None,
                   latlon_range=None,
                   central_longitude=180,
                   lon_ticks=[60, 120, 180, 240, 300],
                   lat_ticks=[-90, -45, 0, 45, 90],
                   land_color=sns.xkcd_rgb['light grey'],
                   ocean_color=sns.xkcd_rgb['light grey'],
                   land_zorder=None,
                   ocean_zorder=None,
                   signif_values=None,
                   signif_range=[0.05, 9999],
                   hatch='..',
                   clim=None,
                   cmap=None,
                   cmap_under=None,
                   cmap_over=None,
                   extend=None,
                   mode='latlon',
                   add_gridlines=False,
                   make_cbar=True,
                   cbar_labels=None,
                   cbar_pad=0.05,
                   cbar_orientation='vertical',
                   cbar_aspect=10,
                   cbar_fraction=0.15,
                   cbar_shrink=0.5,
                   cbar_title=None,
                   font_scale=1.5,
                   plot_type=None,
                   fig=None,
                   ax=None):

    if plot_type == 'corr':
        clim = [-1, 1] if clim is None else clim
        levels = np.linspace(-1, 1, 21) if levels is None else levels
        cbar_labels = np.linspace(-1, 1,
                                  11) if cbar_labels is None else cbar_labels
        cbar_title = 'r' if cbar_title is None else cbar_title
        extend = 'neither' if extend is None else extend
        cmap = 'RdBu_r' if cmap is None else cmap
    elif plot_type == 'R2':
        clim = [0, 1] if clim is None else clim
        levels = np.linspace(0, 1, 21) if levels is None else levels
        cbar_labels = np.linspace(0, 1,
                                  11) if cbar_labels is None else cbar_labels
        cbar_title = r'R$^2$' if cbar_title is None else cbar_title
        extend = 'neither' if extend is None else extend
        cmap = 'Reds' if cmap is None else cmap
    else:
        extend = 'both' if extend is None else extend
        cmap = 'RdBu_r' if cmap is None else cmap

    if add_cyclic_point:
        if mode == 'latlon':
            field_var_c, lon_c = cutil.add_cyclic_point(field_var, lon)
            if signif_values is not None:
                signif_values_c, lon_c = cutil.add_cyclic_point(
                    signif_values, lon)
            lat_c = lat
        elif mode == 'mesh':
            if len(np.shape(lat)) == 1:
                lon, lat = np.meshgrid(lon, lat, sparse=False, indexing='xy')
            if central_longitude == 180:
                lon = np.mod(lon + 180, 360) - 180

            nx, ny = np.shape(field_var)

            lon_c = np.ndarray((nx, ny + 1))
            lat_c = np.ndarray((nx, ny + 1))
            field_var_c = np.ndarray((nx, ny + 1))
            if signif_values is not None:
                signif_values_c = np.ndarray((nx, ny + 1))

            lon_c[:, :-1] = lon
            lon_c[:, -1] = lon[:, 0]

            lat_c[:, :-1] = lat
            lat_c[:, -1] = lat[:, 0]

            field_var_c[:, :-1] = field_var
            field_var_c[:, -1] = field_var[:, 0]

            if signif_values is not None:
                signif_values_c[:, :-1] = signif_values
                signif_values_c[:, -1] = signif_values[:, 0]
    else:
        field_var_c, lat_c, lon_c = field_var, lat, lon
        if signif_values is not None:
            signif_values_c = signif_values

    if ax is None or fig is None:
        fig = plt.figure(figsize=figsize)

        proj_args = {} if proj_args is None else proj_args
        proj_args_default = {'central_longitude': central_longitude}
        proj_args_default.update(proj_args)
        projection = CartopySettings.projection_dict[projection](
            **proj_args_default)
        ax = plt.subplot(projection=projection)

    if title:
        plt.title(title, fontsize=title_size, fontweight=title_weight)

    if latlon_range:
        lon_min, lon_max, lat_min, lat_max = latlon_range
        ax.set_extent(latlon_range, crs=transform)
        lon_formatter = LongitudeFormatter(zero_direction_label=False)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
        lon_ticks = np.array(lon_ticks)
        lat_ticks = np.array(lat_ticks)
        mask_lon = (lon_ticks >= lon_min) & (lon_ticks <= lon_max)
        mask_lat = (lat_ticks >= lat_min) & (lat_ticks <= lat_max)
        ax.set_xticks(lon_ticks[mask_lon], crs=ccrs.PlateCarree())
        ax.set_yticks(lat_ticks[mask_lat], crs=ccrs.PlateCarree())
    else:
        ax.set_global()

    ax.add_feature(cfeature.LAND,
                   facecolor=land_color,
                   edgecolor=land_color,
                   zorder=land_zorder)
    ax.add_feature(cfeature.OCEAN,
                   facecolor=ocean_color,
                   edgecolor=ocean_color,
                   zorder=ocean_zorder)
    ax.coastlines()

    if add_gridlines:
        ax.gridlines(edgecolor='gray', linestyle=':', crs=transform)

    cmap = plt.get_cmap(cmap)
    if cmap_under is not None:
        cmap.set_under(cmap_under)
    if cmap_over is not None:
        cmap.set_over(cmap_over)

    if mode == 'latlon':
        im = ax.contourf(lon_c,
                         lat_c,
                         field_var_c,
                         levels,
                         transform=transform,
                         cmap=cmap,
                         extend=extend)

    elif mode == 'mesh':
        if type(levels) is int:
            levels = MaxNLocator(nbins=levels).tick_values(
                np.nanmax(field_var_c), np.nanmin(field_var_c))
        norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)

        im = ax.pcolormesh(lon_c,
                           lat_c,
                           field_var_c,
                           transform=transform,
                           cmap=cmap,
                           norm=norm)

    if clim:
        im.set_clim(clim)

    if signif_values is not None:
        ax.contourf(lon_c,
                    lat_c,
                    signif_values_c,
                    signif_range,
                    transform=transform,
                    hatches=[hatch],
                    colors='none')

    if make_cbar:
        cbar = fig.colorbar(im,
                            ax=ax,
                            orientation=cbar_orientation,
                            pad=cbar_pad,
                            aspect=cbar_aspect,
                            extend=extend,
                            fraction=cbar_fraction,
                            shrink=cbar_shrink)

        if cbar_labels is not None:
            cbar.set_ticks(cbar_labels)

        if cbar_title:
            cbar.ax.set_title(cbar_title)

    if site_lats is not None and site_lons is not None:
        if type(site_lats) is not dict:
            ax.scatter(site_lons,
                       site_lats,
                       s=site_markersize,
                       c=site_color,
                       marker=site_marker,
                       edgecolors='k',
                       zorder=99,
                       transform=transform)
        else:
            for name in site_lats.keys():
                ax.scatter(site_lons[name],
                           site_lats[name],
                           s=site_markersize[name],
                           c=site_color[name],
                           marker=site_marker[name],
                           edgecolors='k',
                           zorder=99,
                           transform=transform)

    return fig, ax