示例#1
0
    def __init__(self, **proj_info):

        mpl.use(MPL_BACKEND)
        import matplotlib.pyplot as plt

        if not proj_info:
            proj_info = {
                'central_latitude': 58,
                'central_longitude': 16,
                'satellite_height': 35785831,
                'false_easting': 0,
                'false_northing': 0,
                'globe': None
            }

        fig = plt.figure(figsize=(8, 6))

        self._ax = fig.add_subplot(
            1, 1, 1, projection=ccrs.NearsidePerspective(**proj_info))

        self._ax.add_feature(cfeature.OCEAN, zorder=0)
        self._ax.add_feature(cfeature.LAND, zorder=0, edgecolor='black')
        self._ax.add_feature(cfeature.BORDERS, zorder=0)

        self._ax.set_global()
        self._ax.gridlines()
示例#2
0
    def setUp(self):
        self.latitude_of_projection_origin = 0.0
        self.longitude_of_projection_origin = 0.0
        self.perspective_point_height = 38204820000.0
        self.false_easting = 0.0
        self.false_northing = 0.0

        self.semi_major_axis = 6377563.396
        self.semi_minor_axis = 6356256.909
        self.ellipsoid = GeogCS(self.semi_major_axis, self.semi_minor_axis)
        self.globe = ccrs.Globe(semimajor_axis=self.semi_major_axis,
                                semiminor_axis=self.semi_minor_axis,
                                ellipse=None)

        # Actual and expected coord system can be re-used for
        # VerticalPerspective.test_crs_creation and test_projection_creation.
        self.expected = ccrs.NearsidePerspective(
            central_longitude=self.longitude_of_projection_origin,
            central_latitude=self.latitude_of_projection_origin,
            satellite_height=self.perspective_point_height,
            false_easting=self.false_easting,
            false_northing=self.false_northing,
            globe=self.globe)
        self.vp_cs = VerticalPerspective(self.latitude_of_projection_origin,
                                         self.longitude_of_projection_origin,
                                         self.perspective_point_height,
                                         self.false_easting,
                                         self.false_northing, self.ellipsoid)
示例#3
0
def nearside_perspective(experiment: Experiment):
    proj = ccrs.NearsidePerspective(experiment.grid.target_lon,
                                    experiment.grid.target_lat)
    ax = plt.subplot(1, 1, 1, projection=proj)
    ax.set_global()
    ax.coastlines(linewidth=0.8)
    figax = FigureAxes(ax, proj)
    return figax
示例#4
0
    def as_cartopy_crs(self):
        globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe())

        return ccrs.NearsidePerspective(
            central_latitude=self.latitude_of_projection_origin,
            central_longitude=self.longitude_of_projection_origin,
            satellite_height=self.perspective_point_height,
            false_easting=self.false_easting,
            false_northing=self.false_northing,
            globe=globe)
def test_central_latitude():
    # Check the effect of the added 'central_latitude' key.
    geos = ccrs.NearsidePerspective(central_latitude=53.7)
    other_args = {'a=6378137.0', 'h=35785831', 'lat_0=53.7', 'lon_0=0.0',
                  'units=m', 'x_0=0', 'y_0=0'}
    check_proj_params('nsper', geos, other_args)

    assert_almost_equal(geos.boundary.bounds,
                        (-5476336.098, -5476336.098,
                         5476336.098, 5476336.098),
                        decimal=3)
示例#6
0
def plot_lon_zones(view, **kwargs):

    if view == "full":
        projection = ccrs.NearsidePerspective(central_latitude=60,
                                              central_longitude=30,
                                              satellite_height=8000000)
        # projection = ccrs.Orthographic(central_latitude=50, central_longitude=5)
        # projection = ccrs.Miller()
    elif view == "zoom":
        projection = ccrs.Stereographic(central_latitude=60,
                                        central_longitude=20)
    else:
        raise RuntimeError("unknown view.")

    bootstrap.fig(5, 5)
    ax = plt.axes(projection=projection)
    ax.add_feature(land)

    lat_prev = 87
    for NL in np.arange(2, 60):
        lat = flat(NL)

        ax.plot(
            np.linspace(-180, 180, 1000),
            lat * np.ones(1000),
            transform=ccrs.Geodetic(),
            color="gray",
            lw=0.5,
        )

        dlon = 360 / NL
        for lon in np.arange(0, 360, dlon):
            ax.plot((lon, lon), (lat, lat_prev),
                    transform=ccrs.Geodetic(),
                    color="k",
                    lw=1)

        dlon = 360 / (NL - 1)
        for lon in np.arange(0, 360, dlon):
            ax.plot(
                (lon, lon),
                (lat, lat_prev),
                transform=ccrs.Geodetic(),
                color="gray",
                # ls=":",
                lw=1,
            )

        lat_prev = lat

    if view == "zoom":
        ax.set_extent([-5, 60, 60, 90])

    return plt
def test_default():
    geos = ccrs.NearsidePerspective()
    other_args = {'a=6378137.0', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0',
                  'units=m', 'x_0=0', 'y_0=0'}

    check_proj_params('nsper', geos, other_args)

    assert_almost_equal(geos.boundary.bounds,
                        (-5476336.098, -5476336.098,
                         5476336.098, 5476336.098),
                        decimal=3)
def test_offset():
    geos = ccrs.NearsidePerspective(false_easting=5000000,
                                    false_northing=-123000,)
    other_args = {'a=6378137.0', 'h=35785831', 'lat_0=0.0', 'lon_0=0.0',
                  'units=m', 'x_0=5000000', 'y_0=-123000'}

    check_proj_params('nsper', geos, other_args)

    assert_almost_equal(geos.boundary.bounds,
                        (-476336.098, -5599336.098,
                         10476336.098, 5353336.098),
                        decimal=4)
示例#9
0
def test_smooth_boundary_NearsidePerspective(lon, lat, sat_height):
    lon = -100
    lat = -40
    sat_height = 35785831
    pr = ccrs.NearsidePerspective(central_longitude=lon,
                                  central_latitude=lat,
                                  satellite_height=sat_height)
    # modify the projection with smooth boundary
    pr_mod = _smooth_boundary_NearsidePerspective(pr)

    assert pr.proj4_params == pr_mod.proj4_params
    assert pr.globe == pr_mod.globe
示例#10
0
def quick_reg_plot(cube,figdims=(15,10)):
    
    proj=ccrs.NearsidePerspective(central_latitude=60,central_longitude=-20)

    K=np.shape(cube)[0]
    fig=plt.figure()
    axes=[]
    for i in range(K):
        ax=plt.subplot(1,K,i+1,projection=proj)
        quick_contourf(cube[i],ax=ax)
        ax.set_title(f"Cluster {i+1}")
        axes.append(ax)
    fig.set_figwidth(figdims[0])
    fig.set_figheight(figdims[1])
    return fig,axes
示例#11
0
def plot_30y_area(data = None, mask_res = None, years = 31, cmap= "Reds", save_name = False):
    fig = plt.figure(figsize = (9,27))
    gs = gridspec.GridSpec(3, 1)
    ax = fig.add_subplot(gs[0,0],\
            projection=ccrs.NearsidePerspective(
                            central_latitude=50.72,
                            central_longitude=10.53,
                            satellite_height=10000000.0))

    ax.coastlines(resolution='110m')
    ax.gridlines()
    plot_data = data.t2m.where(mask_res, other = np.nan).max("time")
    pm, ct = area_plot(data= plot_data, ax = ax, \
        levels = np.arange(28, 42, 0.5), \
        contour_levels= np.arange(25,40,2), cmap = cmap,
        landcolor = [0.4,0.4,0.4])
示例#12
0
def make_plot2(arctic_circle_lat,origin_lon,origin_lat,does_this_route_pass_through_arctic,dest_airports,airport_code):
	import matplotlib.pyplot as plt, mpld3
	fig, ax = plt.subplots()
	#ax = plt.plot([4,5,6],[6,4,2],'ok')
	ax = plt.axes(projection=ccrs.NearsidePerspective(central_latitude=80.0,central_longitude=origin_lon))
	ax.stock_img()
	ax.text(0, 90, '+',horizontalalignment='right',transform=ccrs.Geodetic())
	ax.plot(np.linspace(0,359,360), np.ones(360)*arctic_circle_lat,color='black', linewidth=2, ls='--',transform=ccrs.Geodetic())
	ax.text(origin_lon, origin_lat, airport_code, transform=ccrs.Geodetic())
	for i in range(len(dest_airports)):
		if does_this_route_pass_through_arctic[i]:
			ax.plot([origin_lon,np.float(dest_airports.loc[i].lon)],[origin_lat,np.float(dest_airports.loc[i].lat)],color=color_list[route_count],linewidth=2,marker='o',transform=ccrs.Geodetic())
			ax.text(np.float(dest_airports.loc[i].lon),np.float(dest_airports.loc[i].lat),dest_airports.loc[i].code,transform=ccrs.Geodetic())
			route_count += 1
	html_text = mpld3.fig_to_html(fig)
	return html_text
示例#13
0
def quick_contourf(cube,cmap=cm.balance,clevs=None,ax=None):
    
    proj=ccrs.NearsidePerspective(central_latitude=60,central_longitude=-20)
    
    if ax is None:
        fig=plt.figure()
        ax=plt.subplot(1,1,1,projection=proj)
        
    if clevs is None:
        clevs=np.linspace(-abs(cube.data).max(),abs(cube.data).max(),21)
        
    ax.coastlines()
    ax.set_global()

    plot=iplt.contourf(cube, levels=clevs, cmap=cmap,extend="both",axes=ax)
    cbar=plt.colorbar(orientation="horizontal",mappable=plot,ax=ax)
    return plot,ax
示例#14
0
def draw():
    fig = plt.figure(figsize=(60, 30))
    pixelData, lat, long = data()

    north = fig.add_subplot(1, 3, 1, projection=ccrs.Orthographic(0, 90))
    north.gridlines()
    north.coastlines()
    north.stock_img()
    north.imshow(pixelData,
                 vmin=0,
                 vmax=100,
                 transform=ccrs.PlateCarree(),
                 extent=(-180, 180, -90, 90),
                 origin="lower",
                 cmap=colorMap())

    all = fig.add_subplot(1,
                          3,
                          2,
                          projection=ccrs.NearsidePerspective(
                              long, lat, satellite_height=5000000, globe=None))
    all.gridlines()
    all.coastlines()
    all.stock_img()
    all.imshow(pixelData,
               vmin=0,
               vmax=100,
               transform=ccrs.PlateCarree(),
               extent=(-180, 180, 0, 90),
               origin="lower",
               cmap=colorMap())

    south = fig.add_subplot(1, 3, 3, projection=ccrs.Orthographic(180, -90))
    south.gridlines()
    south.coastlines()
    south.stock_img()
    south.imshow(pixelData,
                 vmin=0,
                 vmax=100,
                 transform=ccrs.PlateCarree(),
                 extent=(-180, 180, -90, 0),
                 origin="lower",
                 cmap=colorMap())

    plt.show()
示例#15
0
def make_plot(arctic_circle_lat,origin_lon,origin_lat,does_this_route_pass_through_arctic,dest_airports,airport_code):
	fig=Figure()
	ax=fig.add_subplot(111)
	ax = plt.axes(projection=ccrs.NearsidePerspective(central_latitude=80.0,central_longitude=origin_lon))
	ax.stock_img()
	plt.text(0, 90, '+',horizontalalignment='right',transform=ccrs.Geodetic())
	plt.plot(np.linspace(0,359,360), np.ones(360)*arctic_circle_lat,color='black', linewidth=2, ls='--',transform=ccrs.Geodetic())
	plt.text(origin_lon, origin_lat, airport_code, transform=ccrs.Geodetic())
	N_routes = does_this_route_pass_through_arctic.sum()
	color_list = plt.cm.Set1(np.linspace(0, 1, N_routes))
	route_count = 0
	for i in range(len(dest_airports)):
		if does_this_route_pass_through_arctic[i]:
			plt.plot([origin_lon,np.float(dest_airports.loc[i].lon)],[origin_lat,np.float(dest_airports.loc[i].lat)],color=color_list[route_count],linewidth=2,marker='o',transform=ccrs.Geodetic())
			plt.text(np.float(dest_airports.loc[i].lon),np.float(dest_airports.loc[i].lat),dest_airports.loc[i].code,transform=ccrs.Geodetic())
			route_count += 1
	img = io.BytesIO()  # create the buffer
	plt.savefig(img, format='png')  # save figure to the buffer
	img.seek(0)  # rewind your buffer
	plot_data = urllib.parse.quote(base64.b64encode(img.read()).decode()) # base64 encode & URL-escape
	return plot_data
def heatmap(freq_array,
            export=False,
            dest_fn="wind_history_heatmap",
            is_hu_only=False,
            subtitle=None):

    if subtitle == None:
        subtitle = ""

    freq_array_transparent = np.ma.masked_equal(freq_array, 0)

    projection = ccrs.NearsidePerspective(central_longitude=-55,
                                          central_latitude=30,
                                          satellite_height=10000000)
    lon = np.linspace(-180, 180, 361)  # changed from 179
    lat = np.linspace(-90, 90, 181)  # changed from 89
    Lon, Lat = np.meshgrid(lon, lat)

    fig = plt.figure(figsize=(10, 10))
    ax = plt.axes(projection=projection)
    ax.set_global()
    ax.coastlines()
    mesh = ax.pcolormesh(Lon,
                         Lat,
                         freq_array_transparent,
                         transform=ccrs.PlateCarree())
    plt.colorbar(mesh)
    if is_hu_only:
        plt.title(
            f"Number of Cyclones Producing Hurricane-Force Winds /n {subtitle}",
            fontsize=20)
    else:
        plt.title(f"Number of Cyclones Producing TS-Force Winds \n {subtitle}",
                  fontsize=20)

    if export:
        fig.savefig(f"../results/images/{dest_fn}.jpg")

    return
示例#17
0
def _smooth_boundary_NearsidePerspective(
    central_longitude=0.0,
    central_latitude=0.0,
    satellite_height=35785831,
    false_easting=0,
    false_northing=0,
    globe=None,
):
    proj = ccrs.NearsidePerspective(
        central_longitude=central_longitude,
        central_latitude=central_latitude,
        satellite_height=satellite_height,
        false_easting=false_easting,
        false_northing=false_northing,
        globe=globe,
    )

    # workaround for a smoother outer boundary
    # (https://github.com/SciTools/cartopy/issues/613)

    # Re-implement the cartopy code to figure out the boundary.

    # This is just really a guess....
    WGS84_SEMIMAJOR_AXIS = 6378137.0
    # because I cannot import it above...this should be fixed upstream
    # anyways...

    a = proj.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS
    h = np.float(satellite_height)
    max_x = a * np.sqrt(h / (2 * a + h))
    coords = ccrs._ellipse_boundary(max_x,
                                    max_x,
                                    false_easting,
                                    false_northing,
                                    n=361)
    proj._boundary = sgeom.LinearRing(coords.T)
    return proj
示例#18
0
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

plt.figure(figsize=(3, 3))
ax = plt.axes(projection=ccrs.NearsidePerspective(central_latitude=50.72,
                                                  central_longitude=-3.53,
                                                  satellite_height=10000000.0))
ax.coastlines(resolution='110m')
ax.gridlines()
示例#19
0
################
# begin

opj = os.path.join

dirL3 = "L3_summer"
# from oc_tool import utils as u
projet = '/local/AIX/tristan.harmel/project/ardyna/'

odirfig = opj(projet, 'fig/yearly')

# load image data
# ds = xr.open_mfdataset(files, concat_dim='time', preprocess=u.get_time, mask_and_scale=True)
# ds = ds.dropna('time', how='all')
crs = ccrs.NearsidePerspective(100, 71)
land_feat = cpy.feature.NaturalEarthFeature(
    'physical',
    'land',
    '50m',
    edgecolor='face',
    facecolor=cpy.feature.COLORS['land'])
extent = [90, 180, 71, 78]
# file = files[14]
crs = ccrs.PlateCarree()
crs1 = ccrs.NorthPolarStereo()
# crs1 = ccrs.NearsidePerspective(100, 71)
params = ['chlor_a_mean', 'chlor_a_sigma', 'num_obs']
params = ['chlor_a_p50_mean_mean', 'chlor_a_p50_sigma', 'num_obs_mean']

if not os.path.exists(odirfig):
示例#20
0
def trajPlot(root, grids=True, title=None, zscores=None):

    fig = plt.figure(figsize=[10, 8])  # setup fig
    ax = fig.add_subplot(projection=ccrs.NearsidePerspective(-38,
                                                             72))  # subplots
    fig.subplots_adjust(
        top=0.970,  # adjust sizing
        bottom=0.012,
        left=.002,
        right=.981,
        hspace=0.27,
        wspace=0.02)
    ax.coastlines(zorder=3)  # add coastlines
    ax.stock_img()  # stock background
    if grids is True:
        ax.gridlines()  # gridlines

    ax.set_title(title)

    # plot summit
    ax.plot(-38.4592,
            72.5796,
            marker='*',
            color='orange',
            markersize=10,
            alpha=0.9,
            transform=ccrs.Geodetic(),
            label='Summit')

    # create colormap
    cmap = cm.winter  # cmap
    colors = cmap(np.arange(256))  # color linspace
    minz = min(zscores['zscores'].values)  # max and min z scores
    maxz = max(zscores['zscores'].values)
    zscorechart = np.linspace(minz, maxz,
                              num=256)  # equal z score linspace to match

    # plot trajectories
    frame = []
    for filename in os.listdir(root):
        colnames = [
            'recep', 'v2', 'yr', 'mo', 'dy', 'hr', 'na', 'na1', 'backhrs',
            'lat', 'long', 'alt', 'pres'
        ]
        data = pd.read_csv(
            root + '\\' + filename,
            header=None,  # read trajectories
            delim_whitespace=True,
            error_bad_lines=False,
            names=colnames)

        data.dropna(axis=0, how='any', inplace=True)  # drop NaNs
        badcols = ['recep', 'v2', 'na', 'na1']  # drop poor columns
        data.drop(badcols, axis=1, inplace=True)
        data.reset_index(drop=True, inplace=True)

        data['datetime'] = createDatetime(
            data['yr'].values,  # create datetimes
            data['mo'].values,
            data['dy'].values,
            data['hr'].values)
        data.drop(['yr', 'mo', 'dy', 'hr'], axis=1,
                  inplace=True)  # drop old dates

        merged = pd.merge_asof(
            data.sort_values('datetime'),
            zscores,  # merge with zscores
            on='datetime',
            direction='nearest',
            tolerance=pd.Timedelta('1 hours'))

        frame.append(merged)  # append to frame

        track = sgeom.LineString(zip(data['long'].values,
                                     data['lat'].values))  # create trajectory

        currentz = np.nanmax(
            merged['zscores'].values)  # identify z value of trajectory
        nearmatch = zscorechart.flat[np.abs(
            zscorechart - currentz).argmin()]  # identify nearest match
        index = np.where(
            zscorechart == nearmatch)[0][0]  # identify index in zscorechart
        z_color = tuple(colors[index].tolist())  # backsearch for color tuple

        ax.add_geometries(
            [track],
            ccrs.PlateCarree(),  # add to plot
            facecolor='none',
            edgecolor=z_color,
            linewidth=0.5,
            label='Trajectories')

    traj = pd.concat(frame, axis=0, ignore_index=True)  # concat plots

    # plot fires
    fire = fireData()  # import fire data
    matches = []  # matches preallocated

    for row in fire.iterrows():  # loop thru each fire

        decplace = 0  # num of decimal places to match to
        # identify if fire is in a back trajectory path at same times
        lats = np.in1d(np.around(traj['lat'].values, decplace),
                       np.around(row[1]['latitude'], decplace))

        longs = np.in1d(np.around(traj['long'].values, decplace),
                        np.around(row[1]['longitude'], decplace))

        combos = traj[lats & longs].values.tolist()  # lat/long at same time
        matches.append(combos)  # append the combo

        projection = ccrs.Geodetic()  # fire projection to use
        if combos:
            ax.plot(
                row[1]['longitude'],
                row[1]['latitude'],  # if combo, make purple
                marker='.',
                color='purple',
                markersize=8,
                alpha=0.7,
                transform=projection)
        else:
            ax.plot(
                row[1]['longitude'],
                row[1]['latitude'],  # else, make red
                marker='.',
                color='red',
                markersize=4,
                alpha=0.7,
                transform=projection)

    # create colorbar
    cbar_ax = fig.add_axes([.88, 0.15, 0.05, 0.7])  # add fig axes
    norm = mpl.colors.Normalize(vmin=minz, vmax=maxz)  # normalize units
    cb = mpl.colorbar.ColorbarBase(
        cbar_ax,
        cmap=cmap,  # create the colorbar
        orientation='vertical',
        norm=norm)
    cb.set_label('Z-Score Magnitude')  # give title

    legend_elements = [
        mpatches.Rectangle((0, 0), 1, 1,
                           facecolor='orange'),  # create legend elements
        mpatches.Rectangle((0, 0), 1, 1, facecolor='red'),
        mpatches.Rectangle((0, 0), 1, 1, facecolor='purple'),
        mpatches.Rectangle((0, 0), 1, 1, facecolor=tuple(colors[0].tolist()))
    ]

    labels = [
        'Summit',
        'VIIRS Fires',
        'Intersected Fire',  # label creation
        'Trajectory'
    ]

    ax.legend(
        handles=legend_elements,
        loc='lower left',  # create legend
        fancybox=True,
        labels=labels,
        bbox_to_anchor=(-0.1, 0.01))

    matches = pd.DataFrame(matches)  # dataframe matches
    matches.dropna(axis=0, how='any', inplace=True)  # drop nans
    print(f'{len(matches.columns)} intersections were '
          f'found between a back trajectory and a fire')

    plt.show()
def GenerateBasemapImageAutomated(DataDirectory,
                                  RasterFile,
                                  FigWidthInches=4,
                                  FigHeightInches=3,
                                  FigFormat="png",
                                  fig_dpi=500,
                                  regional_extent_multiplier=5,
                                  label_spacing_multiplier=0.5,
                                  out_fname_prefix="",
                                  is_orthographic=False):
    """
    This makes the basemap image. Uses data from the raster to size the figure and locate the centrepoint

    Args:
        DataDirectory (str): The directory of the raster file
        RasterFile (str): the name of the raster file (include extension)
        FigWidthInches (flt): How wide you want the basemap
        FigHeightInches (float): How high you want your basemap
        FigFormat (str): Figure format, can be `png`, `svg`, `pdf`, etc.
        fig_dpi (int): Dots per inch of your figure
        regional_extent_multiplier (float): How much bigger you want the extent vs the size of the raster
        label_spacing_multiplier (float): If the meridians and parallels are too close, increase this number. Default of 0.5
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix


    Author: SMM

    Date: 01/02/2018
    """

    # Make sure data directory is in correct format
    if not DataDirectory.endswith(os.sep):
        print(
            "You forgot the separator at the end of the directory, appending..."
        )
        DataDirectory = DataDirectory + os.sep

    # Set up the figure. This is needed to both size the figure and get the axis handle for plotting polygons
    fig = plt.figure(figsize=(FigWidthInches, FigHeightInches))

    print("The size is: " + str(FigWidthInches) + ", " + str(FigHeightInches))

    # get some filenames
    RasterSplit = RasterFile.split(".")
    Raster_prefix = RasterSplit[0]
    Shape_name = DataDirectory + Raster_prefix + "_footprint.shp"
    SName = "Shape"

    # Get the name of the image
    if len(out_fname_prefix) == 0:
        FigFileName = DataDirectory + Base_file + "_basemap." + FigFormat
    else:
        FigFileName = DataDirectory + out_fname_prefix + "_basemap." + FigFormat

    # Now we get the extents from the raster
    centre_lat, centre_long, extent_lat, extent_long, xproj_extent, yproj_extent = LSDMGDAL.GetCentreAndExtentOfRaster(
        DataDirectory, RasterFile)

    # Calculate the aspect ratio
    aspect_ratio = BasemapExtentSizer(FigWidthInches, FigHeightInches)

    # Figure out the longest dimension
    long_dimension = xproj_extent
    if yproj_extent > long_dimension:
        long_dimension = yproj_extent

    print("The long dimension is: " + str(long_dimension))

    # Get the full extent by mulitplying the longest extent by the multiplier
    full_dimension = long_dimension * regional_extent_multiplier

    # now get the two dimensions for the extent of the figure
    print("The aspect ratio is: " + str(aspect_ratio))
    if aspect_ratio > 1:
        # This is when the figure is wider than tall
        x_ext = full_dimension * aspect_ratio
        y_ext = full_dimension
        full_extent_long = extent_long * aspect_ratio * regional_extent_multiplier
        full_extent_lat = extent_long * regional_extent_multiplier
    else:
        x_ext = full_dimension
        y_ext = full_dimension * aspect_ratio
        full_extent_long = extent_lat * regional_extent_multiplier
        full_extent_lat = extent_lat * aspect_ratio * regional_extent_multiplier

    extents = [
        centre_long - 0.5 * full_extent_long,
        centre_long + 0.5 * full_extent_long,
        centre_lat - 0.5 * full_extent_lat, centre_lat + 0.5 * full_extent_lat
    ]

    print("Extents are: ")
    print(extents)

    # Now we set up the extents and coordinate system
    #if (is_orthographic):
    #    ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.Orthographic(centre_lat, #centre_long))
    #
    #    ax.add_feature(cfeature.LAND)
    #    ax.add_feature(cfeature.OCEAN, edgecolor='black')
    #    ax.set_global()
    #    ax.gridlines()
    if (is_orthographic):
        print("I am setting up an orthographic projection.")
        ax = fig.add_axes([0, 0, 1, 1],
                          projection=ccrs.NearsidePerspective(
                              central_latitude=centre_lat,
                              central_longitude=centre_long,
                              satellite_height=10000000.0))

        ax.coastlines(resolution='110m', linewidth=0.5)
        borders_110m = cfeature.NaturalEarthFeature(
            'cultural',
            'admin_0_boundary_lines_land',
            '110m',
            edgecolor='face',
            facecolor=cfeature.COLORS['land'])
        ax.add_feature(borders_110m,
                       edgecolor='black',
                       facecolor="none",
                       linewidth=0.5)
        ax.gridlines()

    else:
        print("The projection is not orthographic.")
        ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.PlateCarree())

        print("Setting extent.")
        ax.set_extent(extents, ccrs.PlateCarree())
        print("Finished setting extent.")

        land_50m = cfeature.NaturalEarthFeature(
            'physical',
            'land',
            '50m',
            edgecolor='face',
            facecolor=cfeature.COLORS['land'])
        borders_50m = cfeature.NaturalEarthFeature(
            'cultural',
            'admin_0_boundary_lines_land',
            '50m',
            edgecolor='face',
            facecolor=cfeature.COLORS['land'])
        ax.add_feature(land_50m, edgecolor='black', linewidth=0.5)
        ax.add_feature(borders_50m,
                       edgecolor='black',
                       facecolor="none",
                       linewidth=0.5)
        #ax.add_feature(cfeature.LAND)
        #ax.add_feature(cfeature.OCEAN)
        #ax.add_feature(cfeature.COASTLINE)
        #ax.add_feature(cfeature.BORDERS, linestyle='--')
        #ax.add_feature(cfeature.LAKES, alpha=0.5)
        #ax.add_feature(cfeature.RIVERS)

    # create the shapefile
    print("Making the shapefile.")
    LSDMGDAL.CreateShapefileOfRasterFootprint(DataDirectory, RasterFile)

    ax.add_geometries(shpreader.Reader(Shape_name).geometries(),
                      ccrs.PlateCarree(),
                      edgecolor='black',
                      facecolor='green',
                      alpha=0.5,
                      linewidth=0.5)

    ax.gridlines(draw_labels=False, dms=True, x_inline=False, y_inline=False)
    #plt.tight_layout()
    plt.savefig(FigFileName, format=FigFormat, dpi=fig_dpi)
示例#22
0
def rotating_globe(da,
                   fig,
                   timestamp,
                   framedim="time",
                   plotmethod=None,
                   plot_variable=None,
                   overlay_variables=None,
                   lon_start=-110,
                   lon_rotations=0.5,
                   lat_start=25,
                   lat_rotations=0,
                   land=False,
                   gridlines=False,
                   coastline=True,
                   style=None,
                   debug=False,
                   **kwargs):

    # rotate lon_rotations times throughout movie and start at lon_start
    lon = np.linspace(0, 360 * lon_rotations, len(da[framedim])) + lon_start
    # Same for lat
    lat = np.linspace(0, 360 * lat_rotations, len(da[framedim])) + lat_start

    # proj = ccrs.Orthographic(lon[timestamp], lat[timestamp])
    # proj = _smooth_boundary_globe(proj)
    # This looks more like a 3D globe in my opinion
    proj = ccrs.NearsidePerspective(central_longitude=lon[timestamp],
                                    central_latitude=lat[timestamp])
    proj = _smooth_boundary_NearsidePerspective(proj)

    subplot_kw = dict(projection=proj)

    # mapping style kwargs
    map_style_kwargs = dict(transform=ccrs.PlateCarree())
    kwargs.update(map_style_kwargs)

    # create axis (TODO:this should be handled by the basic preset )
    ax = fig.subplots(subplot_kw=subplot_kw)
    data = _check_input(da, plot_variable)
    pp = _base_plot(ax,
                    data,
                    timestamp,
                    framedim,
                    plotmethod=plotmethod,
                    **kwargs)

    _set_style(fig, ax, pp, style=style)

    ax.set_title("")
    ax.set_global()

    # set style (TODO: move this to the basic function including the set style)
    if land:
        _add_land(ax, style)

    if coastline:
        _add_coast(ax, style)

    if gridlines:
        gl = ax.gridlines()
        # Increase gridline res
        gl.n_steps = 500
        # for now fixed locations
        gl.xlocator = mticker.FixedLocator(range(-180, 181, 30))
        gl.ylocator = mticker.FixedLocator(range(-90, 91, 30))
    else:
        gl = None
    # i should output this to test the preset. Maybe a dict output for the pp and gl (and potentially others)?

    # need a way to do that for the outline too

    # possibly for future versions, but I need a way to increase results
    # ax.outline_patch.set_visible(False)
    return ax, pp
示例#23
0
def get_map_projection(
        proj_name,
        central_longitude=0.0,
        central_latitude=0.0,
        false_easting=0.0,
        false_northing=0.0,
        globe=None,
        standard_parallels=(20.0, 50.0),
        scale_factor=None,
        min_latitude=-80.0,
        max_latitude=84.0,
        true_scale_latitude=None,
        latitude_true_scale=None,  ### BOTH
        secant_latitudes=None,
        pole_longitude=0.0,
        pole_latitude=90.0,
        central_rotated_longitude=0.0,
        sweep_axis='y',
        satellite_height=35785831,
        cutoff=-30,
        approx=None,
        southern_hemisphere=False,
        zone=15):  #### numeric UTM zone

    proj_name = proj_name.lower()

    if (proj_name == 'albersequalarea'):
        proj = ccrs.AlbersEqualArea(central_longitude=central_longitude,
                                    central_latitude=central_latitude,
                                    false_easting=false_easting,
                                    false_northing=false_northing,
                                    globe=globe,
                                    standard_parallels=standard_parallels)
    elif (proj_name == 'azimuthalequidistant'):
        proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude,
                                         central_latitude=central_latitude,
                                         false_easting=false_easting,
                                         false_northing=false_northing,
                                         globe=globe)
    elif (proj_name == 'equidistantconic'):
        proj = ccrs.EquidistantConic(central_longitude=central_longitude,
                                     central_latitude=central_latitude,
                                     false_easting=false_easting,
                                     false_northing=false_northing,
                                     globe=globe,
                                     standard_parallels=standard_parallels)
    elif (proj_name == 'lambertconformal'):
        proj = ccrs.LambertConformal(
            central_longitude=-96.0,  ##########
            central_latitude=39.0,  ##########
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            secant_latitudes=None,
            standard_parallels=None,  ## default: (33,45)
            cutoff=cutoff)
    elif (proj_name == 'lambertcylindrical'):
        proj = ccrs.LambertCylindrical(central_longitude=central_longitude)
    elif (proj_name == 'mercator'):
        proj = ccrs.Mercator(central_longitude=central_longitude,
                             min_latitude=min_latitude,
                             max_latitude=max_latitude,
                             latitude_true_scale=latitude_true_scale,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe,
                             scale_factor=None)  #########
    elif (proj_name == 'miller'):
        proj = ccrs.Miller(central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'mollweide'):
        proj = ccrs.Mollweide(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'orthographic'):
        proj = ccrs.Orthographic(central_longitude=central_longitude,
                                 central_latitude=central_latitude,
                                 globe=globe)
    elif (proj_name == 'robinson'):
        proj = ccrs.Robinson(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'sinusoidal'):
        proj = ccrs.Sinusoidal(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'stereographic'):
        proj = ccrs.Stereographic(central_latitude=central_latitude,
                                  central_longitude=central_longitude,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  true_scale_latitude=true_scale_latitude,
                                  scale_factor=scale_factor)
    elif (proj_name == 'transversemercator'):
        proj = ccrs.TransverseMercator(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            scale_factor=1.0,  ##########
            approx=approx)
    elif (proj_name == 'utm'):
        proj = ccrs.UTM(zone,
                        southern_hemisphere=southern_hemisphere,
                        globe=globe)
    elif (proj_name == 'interruptedgoodehomolosine'):
        proj = ccrs.InterruptedGoodeHomolosine(
            central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'rotatedpole'):
        proj = ccrs.RotatedPole(
            pole_longitude=pole_longitude,
            pole_latitude=pole_latitude,
            globe=globe,
            central_rotated_longitude=central_rotated_longitude)
    elif (proj_name == 'osgb'):
        proj = ccrs.OSGB(approx=approx)
    elif (proj_name == 'europp'):
        proj = ccrs.EuroPP
    elif (proj_name == 'geostationary'):
        proj = ccrs.Geostationary(central_longitude=central_longitude,
                                  satellite_height=satellite_height,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  sweep_axis=sweep_axis)
    elif (proj_name == 'nearsideperspective'):
        proj = ccrs.NearsidePerspective(central_longitude=central_longitude,
                                        central_latitude=central_latitude,
                                        satellite_height=satellite_height,
                                        false_easting=false_easting,
                                        false_northing=false_northing,
                                        globe=globe)
    elif (proj_name == 'eckerti'):
        proj = ccrs.EckertI(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertii'):
        proj = ccrs.EckertII(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertiii'):
        proj = ccrs.EckertIII(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'eckertiv'):
        proj = ccrs.EckertIV(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertv'):
        proj = ccrs.EckertV(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertvi'):
        proj = ccrs.EckertVI(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'equalearth'):
        proj = ccrs.EqualEarth(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'gnomonic'):
        proj = ccrs.Gnomonic(central_latitude=central_latitude,
                             central_longitude=central_longitude,
                             globe=globe)
    elif (proj_name == 'lambertazimuthalequalarea'):
        proj = ccrs.LambertAzimuthalEqualArea(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            globe=globe,
            false_easting=false_easting,
            false_northing=false_northing)
    elif (proj_name == 'northpolarstereo'):
        proj = ccrs.NorthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    elif (proj_name == 'osni'):
        proj = ccrs.OSNI(approx=approx)
    elif (proj_name == 'southpolarstereo'):
        proj = ccrs.SouthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    else:
        # This is same as "Geographic coordinates"
        proj = ccrs.PlateCarree(central_longitude=central_longitude,
                                globe=globe)

    return proj
示例#24
0
lat_mars = nc["y"][y0:y1]
z_mars = nc["z"][y0:y1, x0:x1]

## plot data

# vmin vmax for pcolormesh
# use percentiles to ignore outliers
lev_moon = (np.percentile(z_moon, 2), np.percentile(z_moon, 99.8))
lev_mars = (np.percentile(z_mars, 1), np.percentile(z_mars, 99.9))

# figure
fig = plt.figure(figsize=(8, 4))

# map projection
moonproj = ccrs.NearsidePerspective(central_latitude=0.,
                                    central_longitude=250,
                                    satellite_height=40000000.0)
marsproj = ccrs.NearsidePerspective(central_latitude=0.,
                                    central_longitude=270,
                                    satellite_height=40000000.0)
contourfproj = ccrs.RotatedPole(pole_longitude=180.)

ax_moon = fig.add_subplot(1, 2, 1, projection=moonproj)
ax_mars = fig.add_subplot(1, 2, 2, projection=marsproj)

plt.tight_layout(rect=[-.2, .12, 1.2, 0.95])
fig.subplots_adjust(wspace=-0.4, hspace=0.)
cax_moon = fig.add_axes([0.06, 0.11, 0.38, 0.03])
cax_mars = fig.add_axes([0.56, 0.11, 0.38, 0.03])

ax_moon.set_global()
示例#25
0
def set_proj(projection='Robinson', proj_default=True):
    """ Set the projection for Cartopy.
    
    Parameters
    ----------
    
    projection : string
        the map projection. Available projections:
        'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea',
        'AzimuthalEquidistant','EquidistantConic','LambertConformal',
        'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic',
        'Sinusoidal','Stereographic','TransverseMercator','UTM',
        'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP',
        'Geostationary','NearsidePerspective','EckertI','EckertII',
        'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic',
        'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo'
    proj_default : bool
        If True, uses the standard projection attributes from Cartopy.
        Enter new attributes in a dictionary to change them. Lists of attributes
        can be found in the Cartopy documentation: 
            https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv
    
    Returns
    -------
        proj : the Cartopy projection object
        
    See Also
    --------
    pyleoclim.utils.mapping.map_all : mapping function making use of the projection
    
    """
    if proj_default is not True and type(proj_default) is not dict:
        raise TypeError(
            'The default for the projections should either be provided' +
            ' as a dictionary or set to True')

    # Set the projection
    if projection == 'Robinson':
        if proj_default is True:
            proj = ccrs.Robinson()
        else:
            proj = ccrs.Robinson(**proj_default)
    elif projection == 'PlateCarree':
        if proj_default is True:
            proj = ccrs.PlateCarree()
        else:
            proj = ccrs.PlateCarree(**proj_default)
    elif projection == 'AlbersEqualArea':
        if proj_default is True:
            proj = ccrs.AlbersEqualArea()
        else:
            proj = ccrs.AlbersEqualArea(**proj_default)
    elif projection == 'AzimuthalEquidistant':
        if proj_default is True:
            proj = ccrs.AzimuthalEquidistant()
        else:
            proj = ccrs.AzimuthalEquidistant(**proj_default)
    elif projection == 'EquidistantConic':
        if proj_default is True:
            proj = ccrs.EquidistantConic()
        else:
            proj = ccrs.EquidistantConic(**proj_default)
    elif projection == 'LambertConformal':
        if proj_default is True:
            proj = ccrs.LambertConformal()
        else:
            proj = ccrs.LambertConformal(**proj_default)
    elif projection == 'LambertCylindrical':
        if proj_default is True:
            proj = ccrs.LambertCylindrical()
        else:
            proj = ccrs.LambertCylindrical(**proj_default)
    elif projection == 'Mercator':
        if proj_default is True:
            proj = ccrs.Mercator()
        else:
            proj = ccrs.Mercator(**proj_default)
    elif projection == 'Miller':
        if proj_default is True:
            proj = ccrs.Miller()
        else:
            proj = ccrs.Miller(**proj_default)
    elif projection == 'Mollweide':
        if proj_default is True:
            proj = ccrs.Mollweide()
        else:
            proj = ccrs.Mollweide(**proj_default)
    elif projection == 'Orthographic':
        if proj_default is True:
            proj = ccrs.Orthographic()
        else:
            proj = ccrs.Orthographic(**proj_default)
    elif projection == 'Sinusoidal':
        if proj_default is True:
            proj = ccrs.Sinusoidal()
        else:
            proj = ccrs.Sinusoidal(**proj_default)
    elif projection == 'Stereographic':
        if proj_default is True:
            proj = ccrs.Stereographic()
        else:
            proj = ccrs.Stereographic(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'InterruptedGoodeHomolosine':
        if proj_default is True:
            proj = ccrs.InterruptedGoodeHomolosine()
        else:
            proj = ccrs.InterruptedGoodeHomolosine(**proj_default)
    elif projection == 'RotatedPole':
        if proj_default is True:
            proj = ccrs.RotatedPole()
        else:
            proj = ccrs.RotatedPole(**proj_default)
    elif projection == 'OSGB':
        if proj_default is True:
            proj = ccrs.OSGB()
        else:
            proj = ccrs.OSGB(**proj_default)
    elif projection == 'EuroPP':
        if proj_default is True:
            proj = ccrs.EuroPP()
        else:
            proj = ccrs.EuroPP(**proj_default)
    elif projection == 'Geostationary':
        if proj_default is True:
            proj = ccrs.Geostationary()
        else:
            proj = ccrs.Geostationary(**proj_default)
    elif projection == 'NearsidePerspective':
        if proj_default is True:
            proj = ccrs.NearsidePerspective()
        else:
            proj = ccrs.NearsidePerspective(**proj_default)
    elif projection == 'EckertI':
        if proj_default is True:
            proj = ccrs.EckertI()
        else:
            proj = ccrs.EckertI(**proj_default)
    elif projection == 'EckertII':
        if proj_default is True:
            proj = ccrs.EckertII()
        else:
            proj = ccrs.EckertII(**proj_default)
    elif projection == 'EckertIII':
        if proj_default is True:
            proj = ccrs.EckertIII()
        else:
            proj = ccrs.EckertIII(**proj_default)
    elif projection == 'EckertIV':
        if proj_default is True:
            proj = ccrs.EckertIV()
        else:
            proj = ccrs.EckertIV(**proj_default)
    elif projection == 'EckertV':
        if proj_default is True:
            proj = ccrs.EckertV()
        else:
            proj = ccrs.EckertV(**proj_default)
    elif projection == 'EckertVI':
        if proj_default is True:
            proj = ccrs.EckertVI()
        else:
            proj = ccrs.EckertVI(**proj_default)
    elif projection == 'EqualEarth':
        if proj_default is True:
            proj = ccrs.EqualEarth()
        else:
            proj = ccrs.EqualEarth(**proj_default)
    elif projection == 'Gnomonic':
        if proj_default is True:
            proj = ccrs.Gnomonic()
        else:
            proj = ccrs.Gnomonic(**proj_default)
    elif projection == 'LambertAzimuthalEqualArea':
        if proj_default is True:
            proj = ccrs.LambertAzimuthalEqualArea()
        else:
            proj = ccrs.LambertAzimuthalEqualArea(**proj_default)
    elif projection == 'NorthPolarStereo':
        if proj_default is True:
            proj = ccrs.NorthPolarStereo()
        else:
            proj = ccrs.NorthPolarStereo(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.OSNI()
        else:
            proj = ccrs.OSNI(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.SouthPolarStereo()
        else:
            proj = ccrs.SouthPolarStereo(**proj_default)
    else:
        raise ValueError('Invalid projection type')

    return proj
示例#26
0
文件: e_CICE.py 项目: AJueling/CESM
def CICE_XMXL_plots(aice, XMXL, lons, lats, MASK, run, i):
    """"""
    year = int(XMXL.time.item() / 365)
    month = int((XMXL.time.item() % 365) / 30)
    filename = f'{path_results}/CICE/CICE_XMXL_video/CICE_XMXL_{run}_{year}_{month}.png'
    if os.path.exists(filename):
        print(f'{filename} exists already')
        return

    f = plt.figure(figsize=(8, 8))
    ax1 = plt.subplot(2,
                      2,
                      1,
                      projection=ccrs.NearsidePerspective(central_latitude=90))
    ax2 = plt.subplot(
        2, 2, 2, projection=ccrs.NearsidePerspective(central_latitude=-90))
    ax3 = plt.subplot(2,
                      2,
                      3,
                      projection=ccrs.NearsidePerspective(satellite_height=1e7,
                                                          central_latitude=90))
    ax4 = plt.subplot(2,
                      2,
                      4,
                      projection=ccrs.NearsidePerspective(
                          satellite_height=1e7, central_latitude=-90))

    for ax in [ax1, ax2]:  # MXL
        im = ax.pcolormesh(XMXL.TLONG,
                           XMXL.TLAT,
                           XMXL.where(MASK > 0) / 100,
                           cmap=cmocean.cm.amp,
                           vmin=0,
                           vmax=500,
                           transform=ccrs.PlateCarree())

    cbar_ax1 = f.add_axes([0.48, 0.57, 0.02, 0.35])
    f.colorbar(im, cax=cbar_ax1, extend='max')

    for ax in [ax3, ax4]:  # ICE
        im = ax.pcolormesh(lons,
                           lats,
                           aice,
                           cmap=cmocean.cm.ice,
                           vmin=0,
                           vmax=100,
                           transform=ccrs.PlateCarree())

    cbar_ax2 = f.add_axes([0.48, 0.08, 0.02, 0.35])
    f.colorbar(im, cax=cbar_ax2)

    cbar_ax1.text(.5,
                  1.08,
                  f'{year} - {month:2d}',
                  ha='center',
                  transform=cbar_ax1.transAxes,
                  fontsize=18)
    cbar_ax1.text(.5,
                  -.16,
                  'maximum mixed layer depth [m]',
                  ha='center',
                  transform=cbar_ax1.transAxes,
                  fontsize=14)
    cbar_ax2.text(.5,
                  1.06,
                  'sea ice cover [%]',
                  ha='center',
                  transform=cbar_ax2.transAxes,
                  fontsize=14)

    for ax in [ax1, ax2, ax3, ax4]:
        ax.add_feature(cartopy.feature.LAND,
                       zorder=2,
                       edgecolor='black',
                       facecolor='lightgrey')
        #     ax.coastlines(resolution='110m')
        ax.gridlines()

    plt.subplots_adjust(left=0.02, right=0.98, top=0.95, bottom=0.05)

    f.savefig(filename)

    copyfile(
        filename,
        f'{path_results}/CICE/CICE_XMXL_video/CICE_XMXL_{run}_no_{i:04d}.png')

    plt.close('all')

    return
示例#27
0
    def plot(self, figname=None, zoom=1, scale=500, U=20):

        lats_bnds = self.polygon.lats
        lons_bnds = self.polygon.lons
        centroid_lat, centroid_lon = self.centroid[:2]

        fig = plt.figure(dpi=200)
        ax = fig.add_subplot(1,
                             1,
                             1,
                             projection=ccrs.NearsidePerspective(
                                 centroid_lon,
                                 centroid_lat,
                                 satellite_height=6.5e7 / zoom))

        ax.set_global()
        # set the gridlines
        ax.gridlines(color='gray',
                     linestyle='--',
                     xlocs=np.arange(-180, 180, 30),
                     ylocs=np.linspace(-80, 80, 9))

        ax.add_feature(cfeature.OCEAN)
        ax.add_feature(cfeature.LAND, zorder=0)
        ax.add_feature(cfeature.COASTLINE)
        ax.add_feature(cfeature.RIVERS, zorder=1)
        ax.add_feature(cfeature.LAKES, zorder=2)

        ax.plot(lons_bnds,
                lats_bnds,
                color='m',
                transform=ccrs.Geodetic(),
                linewidth=1)
        ax.fill(lons_bnds,
                lats_bnds,
                color='coral',
                transform=ccrs.Geodetic(),
                alpha=0.4)

        if 'omega_cartesian' in self.info:

            lons_bnds_min, lons_bnds_max = lons_bnds.min(), lons_bnds.max()
            lats_bnds_min, lats_bnds_max = lats_bnds.min(), lats_bnds.max()

            if np.abs(lons_bnds_min - lons_bnds_max) > 355:
                if self.contains_points([89, 0]):  # North pole
                    lats_bnds_max = 85
                elif self.contains_points([-89, 0]):  # South pole
                    lats_bnds_min = -85

            lats_fill = np.linspace(lats_bnds_min, lats_bnds_max, 10)
            lons_fill = np.linspace(lons_bnds_min, lons_bnds_max, 10)

            lons_mesh, lats_mesh = np.meshgrid(lons_fill, lats_fill)
            lons_flat = lons_mesh.flatten()
            lats_flat = lats_mesh.flatten()

            inplate_flag = self.contains_points(
                np.array([lats_flat, lons_flat]).T)

            lons_inplate = lons_flat[inplate_flag]
            lats_inplate = lats_flat[inplate_flag]
            h_inplate = np.zeros_like(lats_inplate) * u.m

            locations = [lats_inplate * u.deg, lons_inplate * u.deg, h_inplate]
            inplate_vel_en = self.velocity_at(locations, 'geodetic').en
            inplate_ve, inplate_vn = inplate_vel_en[:, 0], inplate_vel_en[:, 1]

            font0 = FontProperties()
            font0.set_size('small')

            q = ax.quiver(lons_inplate,
                          lats_inplate,
                          inplate_ve,
                          inplate_vn,
                          transform=ccrs.PlateCarree(),
                          scale=scale,
                          width=0.004,
                          color='g',
                          regrid_shape=20)
            ax.quiverkey(q,
                         X=0.65,
                         Y=0.85,
                         U=U,
                         label=r'$20 \, mm/yr$',
                         labelpos='E',
                         coordinates='figure',
                         fontproperties=font0)

        if figname is None:
            plt.show()
        else:
            plt.savefig(figname)
示例#28
0
def GenerateBasemapImageAutomated(DataDirectory, RasterFile, FigWidthInches = 4, FigHeightInches = 3, FigFormat = "png", fig_dpi = 500, regional_extent_multiplier = 5, label_spacing_multiplier = 0.5, out_fname_prefix = "", is_orthographic = False):
    """
    This makes the basemap image. Uses data from the raster to size the figure and locate the centrepoint 
    
    Args:
        DataDirectory (str): The directory of the raster file
        RasterFile (str): the name of the raster file (include extension)
        FigWidthInches (flt): How wide you want the basemap
        FigHeightInches (float): How high you want your basemap
        FigFormat (str): Figure format, can be `png`, `svg`, `pdf`, etc.
        fig_dpi (int): Dots per inch of your figure 
        regional_extent_multiplier (float): How much bigger you want the extent vs the size of the raster 
        label_spacing_multiplier (float): If the meridians and parallels are too close, increase this number. Default of 0.5
        out_fname_prefix (str): The prefix of the image file. If blank uses the fname_prefix
    
    
    Author: SMM
    
    Date: 01/02/2018
    """
    
    # Make sure data directory is in correct format
    if not DataDirectory.endswith(os.sep):
        print("You forgot the separator at the end of the directory, appending...")
        DataDirectory = DataDirectory+os.sep
    
    # Set up the figure. This is needed to both size the figure and get the axis handle for plotting polygons
    fig = plt.figure(figsize=(FigWidthInches, FigHeightInches))
    
    print("The size is: " +str(FigWidthInches)+", "+str(FigHeightInches))
    
    # get some filenames
    RasterSplit = RasterFile.split(".")
    Raster_prefix = RasterSplit[0]
    Shape_name = DataDirectory+Raster_prefix+"_footprint.shp"
    SName = "Shape"
    
    # Get the name of the image
    if len(out_fname_prefix) == 0:
        FigFileName = DataDirectory+Base_file+"_basemap."+FigFormat
    else:
        FigFileName = DataDirectory+out_fname_prefix+"_basemap."+FigFormat   
    
    # Now we get the extents from the raster
    centre_lat, centre_long, extent_lat, extent_long, xproj_extent, yproj_extent = LSDMGDAL.GetCentreAndExtentOfRaster(DataDirectory, RasterFile)
    
       
    # Calculate the aspect ratio
    aspect_ratio = BasemapExtentSizer(FigWidthInches,  FigHeightInches)
    
    # Figure out the longest dimension
    long_dimension = xproj_extent
    if yproj_extent > long_dimension:
        long_dimension = yproj_extent
        
    print("The long dimension is: "+str(long_dimension))
    
    # Get the full extent by mulitplying the longest extent by the multiplier
    full_dimension = long_dimension*regional_extent_multiplier
         
        
    # now get the two dimensions for the extent of the figure
    print("The aspect ratio is: "+str(aspect_ratio))
    if aspect_ratio > 1:
        # This is when the figure is wider than tall
        x_ext = full_dimension*aspect_ratio
        y_ext = full_dimension
        full_extent_long = extent_long*aspect_ratio*regional_extent_multiplier
        full_extent_lat = extent_long*regional_extent_multiplier
    else:
        x_ext = full_dimension
        y_ext = full_dimension*aspect_ratio
        full_extent_long = extent_lat*regional_extent_multiplier
        full_extent_lat = extent_lat*aspect_ratio*regional_extent_multiplier
        
    extents = [centre_long-0.5*full_extent_long,
                   centre_long+0.5*full_extent_long,
                   centre_lat-0.5*full_extent_lat,
                   centre_lat+0.5*full_extent_lat]
    
    print("Extents are: ")
    print(extents)

        
    # Now we set up the extents and coordinate system
    #if (is_orthographic):
    #    ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.Orthographic(centre_lat, #centre_long))
    #    
    #    ax.add_feature(cfeature.LAND)
    #    ax.add_feature(cfeature.OCEAN, edgecolor='black')
    #    ax.set_global()
    #    ax.gridlines()       
    if(is_orthographic):
    
        ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.NearsidePerspective(
                        central_latitude=centre_lat,
                        central_longitude=centre_long,
                        satellite_height=10000000.0))
        
        ax.coastlines(resolution='110m',linewidth=0.5)
        borders_110m = cfeature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '110m',edgecolor='face', facecolor=cfeature.COLORS['land'])
        ax.add_feature(borders_110m, edgecolor='black', facecolor = "none",linewidth=0.5)
        ax.gridlines()
     
    else:    
        ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.PlateCarree())
    
        ax.set_extent([centre_long-0.5*full_extent_long,
                   centre_long+0.5*full_extent_long,
                   centre_lat-0.5*full_extent_lat,
                   centre_lat+0.5*full_extent_lat], ccrs.PlateCarree())
        
        land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m',
                                        edgecolor='face',
                                        facecolor=cfeature.COLORS['land'])
        borders_50m = cfeature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '50m',
                                        edgecolor='face',
                                        facecolor=cfeature.COLORS['land'])
        ax.add_feature(land_50m, edgecolor='black', linewidth=0.5)
        ax.add_feature(borders_50m, edgecolor='black', facecolor = "none",linewidth=0.5)
        #ax.add_feature(cfeature.LAND)
        #ax.add_feature(cfeature.OCEAN)
        #ax.add_feature(cfeature.COASTLINE)
        #ax.add_feature(cfeature.BORDERS, linestyle='--')
        #ax.add_feature(cfeature.LAKES, alpha=0.5)
        #ax.add_feature(cfeature.RIVERS)
    
 
    # create the shapefile
    LSDMGDAL.CreateShapefileOfRasterFootprint(DataDirectory, RasterFile)


    
    ax.add_geometries(
        shpreader.Reader(Shape_name).geometries(),
        ccrs.PlateCarree(),edgecolor='black', facecolor='green', alpha=0.5, linewidth=0.5)
    
    #==========================================
    # draw parallels and meridians.    
    # Calculate the spacing of the meridians and parallels
    # THIS IS ALL FROM BASEMAP AND NOT USED BY CARTOPY
    max_latlong_ext = extent_lat
    if extent_long < max_latlong_ext:
        max_latlong_ext = extent_long
    max_latlong_ext = max_latlong_ext*regional_extent_multiplier
    print("The maximum extent is:"+str(max_latlong_ext))
    
    latlong_label_spacing = int(label_spacing_multiplier*max_latlong_ext+0.5)
    print("And the label spacing is: "+str(latlong_label_spacing))
    start_lat = int(centre_lat - max_latlong_ext*2 - 0.5)
    end_lat = int(centre_lat + max_latlong_ext*2+0.5)
    start_long = int(centre_long - max_latlong_ext*2 -0.5)
    end_long = int(centre_long + max_latlong_ext*2+0.5)
          
    # label parallels on right and top
    # meridians on bottom and left   
    parallels = np.arange(start_lat,end_lat,latlong_label_spacing)
    # labels = [left,right,top,bottom]
    #m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(start_long,end_long,latlong_label_spacing)
    #m.drawmeridians(meridians,labels=[True,False,False,True])
    #==========================================
    
    #==========================================
    # THIS IS ALL FROM BASEMAP AND NOT USED BY CARTOPY
    # Make a patch from the shapefile
    # All this stuff from:
    # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/
    #df_poly = pd.DataFrame({
    #        'shapes': [Polygon(np.array(shape), True) for shape in m.footprint]})    
    
    #df_poly = df_poly.merge(new_areas, on='area', how='left')
    #cmap = plt.get_cmap('Oranges')   
    #pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5)
    #pc.set_facecolor("crimson")
    #ax.add_collection(pc)
    #==========================================

    plt.savefig(FigFileName,format=FigFormat,dpi=fig_dpi)    
示例#29
0
    def projection(self):
        if self.proj is None:
            return ccrs.PlateCarree()

        proj_dict = ast.literal_eval(self.proj)
        user_proj = proj_dict.pop("proj")
        if user_proj == 'PlateCarree':
            self.xylim_supported = True
            return ccrs.PlateCarree(**proj_dict)
        elif user_proj == 'AlbersEqualArea':
            return ccrs.AlbersEqualArea(**proj_dict)
        elif user_proj == 'AzimuthalEquidistant':
            return ccrs.AzimuthalEquidistant(**proj_dict)
        elif user_proj == 'EquidistantConic':
            return ccrs.EquidistantConic(**proj_dict)
        elif user_proj == 'LambertConformal':
            return ccrs.LambertConformal(**proj_dict)
        elif user_proj == 'LambertCylindrical':
            return ccrs.LambertCylindrical(**proj_dict)
        elif user_proj == 'Mercator':
            return ccrs.Mercator(**proj_dict)
        elif user_proj == 'Miller':
            return ccrs.Miller(**proj_dict)
        elif user_proj == 'Mollweide':
            return ccrs.Mollweide(**proj_dict)
        elif user_proj == 'Orthographic':
            return ccrs.Orthographic(**proj_dict)
        elif user_proj == 'Robinson':
            return ccrs.Robinson(**proj_dict)
        elif user_proj == 'Sinusoidal':
            return ccrs.Sinusoidal(**proj_dict)
        elif user_proj == 'Stereographic':
            return ccrs.Stereographic(**proj_dict)
        elif user_proj == 'TransverseMercator':
            return ccrs.TransverseMercator(**proj_dict)
        elif user_proj == 'UTM':
            return ccrs.UTM(**proj_dict)
        elif user_proj == 'InterruptedGoodeHomolosine':
            return ccrs.InterruptedGoodeHomolosine(**proj_dict)
        elif user_proj == 'RotatedPole':
            return ccrs.RotatedPole(**proj_dict)
        elif user_proj == 'OSGB':
            self.xylim_supported = False
            return ccrs.OSGB(**proj_dict)
        elif user_proj == 'EuroPP':
            self.xylim_supported = False
            return ccrs.EuroPP(**proj_dict)
        elif user_proj == 'Geostationary':
            return ccrs.Geostationary(**proj_dict)
        elif user_proj == 'NearsidePerspective':
            return ccrs.NearsidePerspective(**proj_dict)
        elif user_proj == 'EckertI':
            return ccrs.EckertI(**proj_dict)
        elif user_proj == 'EckertII':
            return ccrs.EckertII(**proj_dict)
        elif user_proj == 'EckertIII':
            return ccrs.EckertIII(**proj_dict)
        elif user_proj == 'EckertIV':
            return ccrs.EckertIV(**proj_dict)
        elif user_proj == 'EckertV':
            return ccrs.EckertV(**proj_dict)
        elif user_proj == 'EckertVI':
            return ccrs.EckertVI(**proj_dict)
        elif user_proj == 'EqualEarth':
            return ccrs.EqualEarth(**proj_dict)
        elif user_proj == 'Gnomonic':
            return ccrs.Gnomonic(**proj_dict)
        elif user_proj == 'LambertAzimuthalEqualArea':
            return ccrs.LambertAzimuthalEqualArea(**proj_dict)
        elif user_proj == 'NorthPolarStereo':
            return ccrs.NorthPolarStereo(**proj_dict)
        elif user_proj == 'OSNI':
            return ccrs.OSNI(**proj_dict)
        elif user_proj == 'SouthPolarStereo':
            return ccrs.SouthPolarStereo(**proj_dict)
示例#30
0
def plot_map_and_stations(fig,
                          gridspec,
                          station_locations,
                          station_names,
                          station_plot_dict,
                          region_corners=None,
                          ss_location=None,
                          date=None):
    map_ax = fig.add_subplot(gridspec,
                             projection=ccrs.NearsidePerspective(
                                 -95, 57, 15000000))
    map_ax.stock_img()
    # Plot the border of region
    if region_corners is not None:
        map_ax.plot(np.linspace(region_corners[0][0], region_corners[1][0],
                                10),
                    np.ones(10) * region_corners[0][1],
                    '--',
                    color='gray',
                    transform=ccrs.PlateCarree())

        map_ax.plot(np.ones(10) * region_corners[1][0],
                    np.linspace(region_corners[0][1], region_corners[1][1],
                                10),
                    '--',
                    color='gray',
                    transform=ccrs.PlateCarree())

        map_ax.plot(np.linspace(region_corners[0][0], region_corners[1][0],
                                10),
                    np.ones(10) * region_corners[1][1],
                    '--',
                    color='gray',
                    transform=ccrs.PlateCarree())

        map_ax.plot(np.ones(10) * region_corners[0][0],
                    np.linspace(region_corners[0][1], region_corners[1][1],
                                10),
                    '--',
                    color='gray',
                    transform=ccrs.PlateCarree())

    # plot all stations
    map_ax.plot(station_locations[:, 0],
                station_locations[:, 1],
                '.',
                color='black',
                transform=ccrs.PlateCarree())
    # plot special stations
    for entry in station_plot_dict:
        map_ax.plot(station_locations[entry['indices'], 0],
                    station_locations[entry['indices'], 1],
                    '.',
                    color=entry['color'],
                    transform=ccrs.PlateCarree(),
                    label=entry['name'])
        if entry['station names']:
            for j in entry['indices']:
                map_ax.text(station_locations[j, 0] - 1,
                            station_locations[j, 1] - 1,
                            station_names[j],
                            horizontalalignment='right',
                            transform=ccrs.PlateCarree())

    map_ax.legend()

    if ss_location is not None:
        map_ax.plot(ss_location[0],
                    ss_location[1],
                    'rx',
                    transform=ccrs.PlateCarree())

    if date is not None:
        map_ax.add_feature(Nightshade(date, alpha=0.2))