예제 #1
0
파일: geo.py 프로젝트: zassa/geoviews
    def from_shapefile(cls, shapefile, *args, **kwargs):
        """
        Loads a shapefile from disk and optionally merges
        it with a dataset. See ``from_records`` for full
        signature.

        Parameters
        ----------
        records: list of cartopy.io.shapereader.Record
           Iterator containing Records.
        dataset: holoviews.Dataset
           Any HoloViews Dataset type.
        on: str or list or dict
          A mapping between the attribute names in the records and the
          dimensions in the dataset.
        value: str
          The value dimension in the dataset the values will be drawn
          from.
        index: str or list
          One or more dimensions in the dataset the Shapes will be
          indexed by.
        drop_missing: boolean
          Whether to drop shapes which are missing from the provides
          dataset.

        Returns
        -------
        shapes: Polygons or Path object
          A Polygons or Path object containing the geometries
        """
        reader = Reader(shapefile)
        return cls.from_records(reader.records(), *args, **kwargs)
예제 #2
0
파일: geo.py 프로젝트: ioam/geoviews
    def from_shapefile(cls, shapefile, *args, **kwargs):
        """
        Loads a shapefile from disk and optionally merges
        it with a dataset. See ``from_records`` for full
        signature.

        Parameters
        ----------
        records: list of cartopy.io.shapereader.Record
           Iterator containing Records.
        dataset: holoviews.Dataset
           Any HoloViews Dataset type.
        on: str or list or dict
          A mapping between the attribute names in the records and the
          dimensions in the dataset.
        value: str
          The value dimension in the dataset the values will be drawn
          from.
        index: str or list
          One or more dimensions in the dataset the Shapes will be
          indexed by.
        drop_missing: boolean
          Whether to drop shapes which are missing from the provides
          dataset.

        Returns
        -------
        shapes: Polygons or Path object
          A Polygons or Path object containing the geometries
        """
        reader = Reader(shapefile)
        return cls.from_records(reader.records(), *args, **kwargs)
예제 #3
0
    def plot_magnetic_picks(self, ax, facecolors='none'):
        for i in range(1, 5):
            reader = Reader(f'{magnetic_picks_output_basename}_{i}')
            #m.readshapefile(magnetic_picks_output_basename+'_{}'.format(i) ,'magnetic_{}'.format(i),drawbounds=False,color='w')
            import hashlib
            colors = []
            lons = []
            lats = []
            for s in reader.records():
                if all(k in s.attributes for k in ['Chron', 'AnomalyEnd']):
                    #not really colouring by plate id. In fact, it is colouring by Chron+AnomalyEnd
                    colors.append(
                        plate_tectonic_utils.get_colour_by_plateid(
                            int(
                                hashlib.sha1((s.attributes['Chron'] +
                                              s.attributes['AnomalyEnd']
                                              ).encode('utf-8')).hexdigest(),
                                16)))
                else:
                    colors.append(
                        plate_tectonic_utils.get_colour_by_plateid(0))
                lons.append(s.geometry.x)
                lats.append(s.geometry.y)

            ax.scatter(
                lons,
                lats,
                facecolors='none',
                edgecolor=colors,
                transform=ccrs.PlateCarree(),
                #s=.1,
                zorder=99)
예제 #4
0
 def from_shapefile(cls, shapefile, *args, **kwargs):
     """
     Loads a shapefile from disk and optionally merges
     it with a dataset. See ``from_records`` for full
     signature.
     """
     reader = Reader(shapefile)
     return cls.from_records(reader.records(), *args, **kwargs)
예제 #5
0
 def shelf(self):
     """returns Mueller ice shelf as :class:`shapely.geometry.Polygon` based on :attr:`coastline_file`"""
     R = Reader(os.path.join(self.path, self.coastline_file))
     recs = [r for r in R.records() if r.attributes['FID_Coastl'] in self.shelf_features]
     # order is important
     geoms = [[r.geometry for r in recs if r.attributes['FID_Coastl']==f][0] for f in self.shelf_features]
     pts = np.hstack([np.r_['1,2', p.xy] for g in geoms for p in g.geoms]).T.tolist()
     # important! planar geometry ('False')
     # https://developers.google.com/earth-engine/geometries_planar_geodesic
     return ee.Geometry.Polygon(pts, 'EPSG:{}'.format(self.quanta_epsg), False)
    def obtain_map_info(self, path):
        """ Return the records (record = (attributes, geometry)) of the shapefile

        Parameters :
        - path = path of the shapefile to read

        CountryMap(*args).obtain_map_info() ==> record :->generator"""
        self.path_shp_commune = path
        reader = Reader(path)
        records = reader.records()
        return records
예제 #7
0
def make_african_land():
    from cartopy.io.shapereader import Reader, natural_earth
    from shapely.ops import unary_union

    shpfile = Reader(natural_earth(resolution='110m', category='cultural', name='admin_0_countries'))

    filtered_records = shpfile.records()
    filtered_records = filter(lambda x: x.attributes['continent'] == 'Africa', filtered_records)

    region_poly = unary_union([r.geometry for r in filtered_records])

    return region_poly
예제 #8
0
    def maskcountries(self,
                      conf,
                      ax=None,
                      regions=["China"],
                      pathkw=dict(facecolor='none',
                                  edgecolor='black',
                                  linewidth=1.5)):
        """
        在cartopy中, 对选定的国家进行白化.
        refer to https://cloud.tencent.com/developer/article/1618341

        Args:
            conf (matplotlib object): matplotlib的contour或contourf绘图返回值.
            ax (object, optional): Axes instance, if not None then overrides the default axes instance.
            regions (list, optional): 指定无需白化的国家. Defaults to ["China"].
            pathkw (dict, optional): PathPatch关键字参数. Defaults to dict(facecolor='none',edgecolor='black', linewidth=1.0).

        Returns:
            clipping path, matplotlib.patches.PathPatch
        """

        #Get current axes if not specified
        ax = ax or self._check_ax()

        #Convert region name to upper
        regions = list(regions)
        regions = [region.upper() for region in regions]

        # get shape file
        shpfile = pkg_resources.resource_filename(
            'nmc_met_graphics', "resources/maps/country1.shp")

        # retrive region geometry
        reader = Reader(shpfile)
        countries = reader.records()
        multipoly, = [
            country.geometry for country in countries
            if country.attributes['CNTRY_NAME'].upper() in regions
        ]

        main_geom = sorted(multipoly.geoms, key=lambda geom: geom.area)[-1]

        path, = geos_to_path(main_geom)

        plate_carre_data_transform = ccrs.PlateCarree()._as_mpl_transform(ax)

        for collection in conf.collections:
            collection.set_clip_path(path, plate_carre_data_transform)

        # Draw the path of interest.
        path = PathPatch(path, transform=ccrs.PlateCarree(), **pathkw)
        return path
예제 #9
0
def addFeatures(fname):
    f = Reader(fname)
    for item in f.records():
        attributes = item.attributes
        geometry = item.geometry
        facecolor, edgecolor, alpha = categorizeBWS_s(attributes, column,
                                                      categories)

        feature = ShapelyFeature(geometry,
                                 ccrs.PlateCarree(),
                                 facecolor=facecolor,
                                 edgecolor=edgecolor,
                                 alpha=alpha)
        ax.add_feature(feature)
예제 #10
0
def make_np_mask(target_header):
    """Generate mask of cells that are in Redwood National Park"""

    rdr = Reader(os.path.join("InputData", "nps_boundary", "nps_boundary.shp"))
    redw_records = []
    for x in rdr.records():
        if 'Redwood' in x.attributes['UNIT_NAME']:
            redw_records.append(x)

    redw_shape_nps = redw_records[0].geometry[0]

    NAD83_Cali_Albers = pyproj.Proj("+init=EPSG:3310")
    nps_proj = pyproj.Proj("+init=EPSG:4269")

    project = partial(pyproj.transform, nps_proj, NAD83_Cali_Albers)

    redw_shape = transform(project, redw_shape_nps)

    lower_x = np.array([
        target_header['xllcorner'] + i * target_header['cellsize']
        for i in range(target_header['ncols'])
    ])
    upper_x = lower_x + target_header['cellsize']

    lower_y = np.array([
        target_header['yllcorner'] + i * target_header['cellsize']
        for i in range(target_header['nrows'])
    ])[::-1]
    upper_y = lower_y + target_header['cellsize']

    np_array = np.zeros((target_header['nrows'], target_header['ncols']))

    for i in range(target_header['nrows']):
        for j in range(target_header['ncols']):
            points = [[lower_x[j], lower_y[i]], [upper_x[j], lower_y[i]],
                      [upper_x[j], upper_y[i]], [lower_x[j], upper_y[i]]]
            cell = geometry.Polygon(points)
            intersection_area = redw_shape.intersection(cell).area / (
                target_header['cellsize'] * target_header['cellsize'])

            np_array[i, j] = intersection_area

    np_raster = raster_tools.RasterData(
        (target_header['nrows'], target_header['ncols']),
        (target_header['xllcorner'], target_header['yllcorner']),
        target_header['cellsize'],
        array=np_array)

    return np_raster
예제 #11
0
def mapa_base(llat, llon):
    """
    Mapa base para graficar las variables
    """

    l_lat = llat
    l_lon = np.array(llon) % 360  #Pasamos lon en [-180, 180] a [0, 360]
    states_provinces = cpf.NaturalEarthFeature(category='cultural',
                            name='admin_1_states_provinces_lines',
                            scale='10m',
                            facecolor='none')
    shp = Reader(natural_earth(resolution='10m', category='cultural',
                               name='admin_1_states_provinces_lines'))
    countries = shp.records()

    # Comenzamos la Figura
    fig = plt.figure(figsize=(6, 8))
    proj_lcc = ccrs.PlateCarree()
    ax = plt.axes(projection=proj_lcc)
    ax.coastlines(resolution='10m')
    ax.add_feature(cpf.BORDERS, linestyle='-')
    #ax.add_feature(states_provinces, edgecolor='gray')
    for country in countries:
        if country.attributes['adm0_name'] == 'Argentina':
            ax.add_geometries( [country.geometry], ccrs.PlateCarree(),
                                edgecolor='black', facecolor='none',
                                linewidth=0.7 )
    # ax.add_feature(shape_feature)
    # Colocamos reticula personalizada
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=0.4, color='gray', alpha=0.7, linestyle=':')
    gl.xlabels_top = False
    gl.ylabels_right = False
    gl.xlocator = mticker.FixedLocator(np.linspace(llon[0], llon[1], 7))
    gl.ylocator = mticker.FixedLocator(np.linspace(l_lat[0], l_lat[1], 9))
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    # Extension del mapa
    ax.set_extent([l_lon[0], l_lon[1], l_lat[0], l_lat[1]], crs=proj_lcc)
    # Posicion del eje (desplazamos un poco a la izquierda y más abajo)
    pos1 = ax.get_position() # get the original position
    pos2 = [pos1.x0 - 0.05, pos1.y0 - 0.06,  pos1.width*1.16, pos1.height*1.22]
    ax.set_position(pos2) # set a new position
    ax.text(-79., -21., 'Fuente:\n NOAA - GFS',
            horizontalalignment='left', verticalalignment='top',
            fontweight='bold', fontsize=13,
            transform=ccrs.Geodetic())
    return fig, ax
예제 #12
0
def shpplt(shp,
           colors,
           ax=None,
           crs=ccrs.PlateCarree(),
           field='type',
           numbered=True,
           **kwargs):
    """
    Plot polygon .shp file from path using variable colors.
    
    Requires that .shp file have field with numerical values that
    will correspond to color.
    
    Parameters:
        shp: Path to .shp file
        colors: List or dict of colors corresponding to field in .shp file
        ax: Axes on which to plot polygon
        crs: Cartopy projection for .shp file
        field: Name of field with values used for color
    
    Retruns:
        df: Pandas dataframe of attribute table from .shp file
    """
    reader = Reader(shp)  # Creates reader object
    units = reader.records()  # Gets records from reader object
    lst = []  # Set up empty list

    for unit in units:  # Iterate over each object in .shp file
        # Get type number from attributes to assign color, requires 'type'
        # field in imported .shp file
        t = unit.attributes[field]
        geo = unit.geometry  # Get geometry to plot

        # Plot geometry using field attribute to assign color

        # If field sequential integers, adapt for Python counting
        if numbered is True:
            ax.add_geometries([geo], crs, facecolor=colors[t - 1], **kwargs)
        # If field non-sequential, use color dictionary
        elif numbered is False:
            ax.add_geometries([geo], crs, facecolor=colors[t], **kwargs)

        # Add attributes to list to create dataframe
        lst.append(unit.attributes)

    df = pd.DataFrame.from_records(lst)  #create dataframe of attribute table

    return (df)
예제 #13
0
def load_plz_records(path=PATH):

    reader = Reader(path)
    recs = list(reader.records())

    return recs
예제 #14
0
# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

fig = plt.figure(figsize=(20, 100))
ax = plt.axes(projection=ccrs.Robinson())
extents = [-20, 20, 30, 40]
ax.coastlines(resolution='50m')
ax.set_extent(extents, crs=None)

test = Reader(fname)
test.records()
for item in test.records():
    attributes = item.attributes
    geometry = item.geometry
    print(type(geometry))
    feature = ShapelyFeature(geometry, ccrs.PlateCarree())
    ax.add_feature(feature)

# In[ ]:

shape_feature = ShapelyFeature(Reader(fname).geometries(),
                               ccrs.PlateCarree(),
                               facecolor='blue',
                               edgecolor='red')
					new_d14c_cube.data = d14c_data_for_cube
					new_dpco2_cube.data = dpco2_data_for_cube
					new_d14c_cube.coord('time').points = (d14c_cube.coord('time').points-11)/100
					new_dpco2_cube.coord('time').points = (d14c_cube.coord('time').points-11)/100
					new_d14c_cube.long_name = d14c_cube.long_name
					new_dpco2_cube.long_name = dpco2_cube.long_name
					new_d14c_cube.standard_name = d14c_cube.standard_name
					new_dpco2_cube.standard_name = dpco2_cube.standard_name
					new_d14c_cube.units = d14c_cube.units
					new_dpco2_cube.units = dpco2_cube.units
					new_d14c_cube.var_name = d14c_cube.var_name
					new_dpco2_cube.var_name = dpco2_cube.var_name

					shpfilename = natural_earth(resolution='110m', category='physical', name='land')
					reader = Reader(shpfilename)
					continents = reader.records()

					new_d14c_cube.coord('latitude').guess_bounds()
					new_d14c_cube.coord('longitude').guess_bounds()
					new_dpco2_cube.coord('latitude').guess_bounds()
					new_dpco2_cube.coord('longitude').guess_bounds()

					continent_geometries = reader.geometries()  # NB. Switched from using records()
					all_continents_geometry = cascaded_union(list(continent_geometries))
					area_weights = geometry_area_weights(new_d14c_cube, all_continents_geometry)
					land_mask = np.where(area_weights > 0, True, False)
					new_d14c_cube.data = np.ma.array(new_d14c_cube.data, mask=land_mask)
					area_weights = geometry_area_weights(new_dpco2_cube, all_continents_geometry)
					land_mask = np.where(area_weights > 0, True, False)
					new_dpco2_cube.data = np.ma.array(new_dpco2_cube.data, mask=land_mask)
import os

plt.clf()

#ax = geo_plots.add_map(bbox=(-89,-85,27.5,31))
ax = geo_plots.add_map(bbox=(-90, -84, 27.5, 31))
#land_10m = cfeature.NaturalEarthFeature('physical','land','50m',\
#    edgecolor='face',facecolor='0.75')
##ax.add_feature(cfeature.LAND, facecolor='0.75')
#ax.add_feature(land_10m)
#if bbox not specified, this will use map bounds from bna

bathy_file = os.path.join('gom_bathy','Bathymetry.shp')
bathy = Reader(bathy_file)

for rec,geo in zip(bathy.records(),bathy.geometries()):
    if rec.attributes['DEPTH_METR'] in ['100m','500m','1000m']:
        shape_feature = ShapelyFeature(geo,ccrs.PlateCarree(), facecolor='none')
        ax.add_feature(shape_feature)

#add particles at one time
t = datetime.datetime(2016, 9, 21, 1)

filename = 'gulf_tamoc.nc'
ax = geo_plots.contour_particles(ax,filename,t,levels=[0.1, 0.4, 0.6, 1])
#ax = geo_plots.plot_particles(ax,filename,t,depth=0,color='b')


#add initial location

예제 #17
0
def plot_part_loc_map(part_pos,
                      release_no,
                      dt,
                      traj,
                      savepath,
                      ls=None,
                      config=None,
                      add_dyn=True,
                      add_fire=None):
    """"""

    release_sel = np.array([list(p) for p in part_pos if p[0] == release_no])
    meta = traj['releases_meta'][release_no]

    import matplotlib
    matplotlib.use('Agg')
    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    from fastkml import kml

    if ls is None:
        ls = trace_source.land_sfc.land_sfc()

    if not os.path.isdir(savepath):
        os.makedirs(savepath)

    if config['plotmap']['maptype'] == 'northpole':
        fig = plt.figure(figsize=(11, 10))
        if "centerlon" in config['plotmap']:
            ax = plt.axes(projection=ccrs.NorthPolarStereo(
                central_longitude=config['plotmap']['centerlon']))
        else:
            ax = plt.axes(projection=ccrs.NorthPolarStereo(
                central_longitude=45))

    if config['plotmap']['maptype'] == 'miller':
        fig = plt.figure(figsize=(10, 7))
        if "centerlon" in config['plotmap']:
            ax = plt.axes(projection=ccrs.Miller(
                central_longitude=config['plotmap']['centerlon']))
        else:
            ax = plt.axes(projection=ccrs.Miller(central_longitude=0))
    else:
        print("using standard map")
        fig = plt.figure(figsize=(10, 7))
        ax = plt.axes(projection=ccrs.Miller(central_longitude=0))

    assert config is not None
    if config is not None and "bounds" in config['plotmap']:
        ax.set_extent(config['plotmap']['bounds'], crs=ccrs.PlateCarree())

    ####
    # make a color map of fixed colors
    colors = [
        'lightskyblue', 'darkgreen', 'khaki', 'palegreen', 'red', 'white',
        'tan'
    ]
    # better green for the light map
    colors = [
        'lightskyblue', 'seagreen', 'khaki', '#6edd6e', 'darkmagenta', 'white',
        'tan'
    ]
    #colors = ['lightskyblue', 'seagreen', 'khaki', '#a4dd6e', 'red', 'white', 'tan']
    colors = [
        'lightskyblue', '#22a361', 'khaki', '#72d472', 'darkmagenta', 'white',
        'tan'
    ]
    cmap = matplotlib.colors.ListedColormap(colors)

    cs = [adjust_lightness(c, amount=1.15) for c in colors]
    print('cs ', cs)
    cmap = matplotlib.colors.ListedColormap(cs)

    bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5]
    norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
    ####
    pcm = ax.pcolormesh(ls.longs,
                        ls.lats,
                        ls.land_sfc_data,
                        cmap=cmap,
                        norm=norm,
                        transform=ccrs.PlateCarree())
    # high resolution coastlines
    #ax.coastlines(resolution='110m')
    ax.coastlines(resolution='50m')
    # ax.coastlines(resolution='10m')

    labels = [
        'Water', 'Forest', 'Savanna/shrubland', 'Grass/cropland', 'Urban',
        'Snow/ice', 'Barren'
    ]
    handles = []
    for c, l in zip(cs, labels):
        if 'ice' in l:
            handles.append(
                matplotlib.patches.Patch(facecolor=c,
                                         label=l,
                                         edgecolor='grey',
                                         linewidth=2))
        else:
            handles.append(matplotlib.patches.Patch(color=c, label=l))

    # # # The modis fire map
    if add_fire:
        from cartopy.io.shapereader import Reader
        from cartopy.feature import ShapelyFeature
        # # fname = '../data/DL_FIRE_M6_78471/fire_nrt_M6_78471.shp'
        #    fname = config_dir['partposit_dir'] + '20191130_DL_FIRE_V1_90092/fire_nrt_V1_90092.shp'
        fname = f'data/fire_data/DL_FIRE_{add_fire}/fire_nrt_{add_fire}.shp'

        shp_data = Reader(fname)
        # print(next(shp_data.records()))
        frp = np.array([p.attributes['FRP'] for p in shp_data.records()])
        # print(frp.shape, np.mean(frp), np.percentile(frp, [10,25,50,75,90]))

        points = [
            p for p in list(shp_data.records()) if p.attributes['FRP'] > 12
        ]
        # # for viirs pixel with their smaller size
        # points = [p for p in list(shp_data.records()) if p.attributes['FRP'] > 4]
        # #points = sorted(points, key=lambda x: x.attributes['FRP'])

        scat = ax.scatter(
            [p.geometry.x for p in points],
            [p.geometry.y for p in points],
            #transform=ccrs.Geodetic(), s=0.5,
            transform=ccrs.PlateCarree(),
            s=0.5,
            c='crimson')

    # optionally add the dynamics from gfs grib
    if add_dyn:
        import xarray as xr

        if dt.hour % 6 == 0:
            gribfile = f"data/gfs_083.2/{dt.strftime('%Y%m%d%H')}"
            print(gribfile)
            if not os.path.isfile(gribfile):
                print('try forecast file')
                gribfile = f"data/gfs_083.2/{dt.strftime('%Y%m%d%H')}_f"

            ds_isobaric = xr.load_dataset(gribfile,
                                          engine='cfgrib',
                                          backend_kwargs={
                                              'filter_by_keys': {
                                                  'typeOfLevel':
                                                  'isobaricInhPa'
                                              },
                                              'errors': 'ignore'
                                          })

            ds_mean_sea = xr.load_dataset(gribfile,
                                          engine='cfgrib',
                                          backend_kwargs={
                                              'filter_by_keys': {
                                                  'typeOfLevel': 'meanSea'
                                              },
                                              'errors': 'ignore'
                                          })

            prmsl = ds_mean_sea.prmsl
            gh_500 = ds_isobaric.gh.sel(isobaricInhPa=500)

        else:
            gribfile1 = f"data/gfs_083.2/{(dt - datetime.timedelta(hours=3)).strftime('%Y%m%d%H')}"
            gribfile2 = f"data/gfs_083.2/{(dt + datetime.timedelta(hours=3)).strftime('%Y%m%d%H')}"
            if not os.path.isfile(gribfile1):
                print('try forecast file')
                gribfile1 = f"data/gfs_083.2/{(dt - datetime.timedelta(hours=3)).strftime('%Y%m%d%H')}_f"
            if not os.path.isfile(gribfile2):
                print('try forecast file')
                gribfile2 = f"data/gfs_083.2/{(dt + datetime.timedelta(hours=3)).strftime('%Y%m%d%H')}_f"
            print(gribfile1, gribfile2)

            ds_isobaric = xr.load_dataset(gribfile1,
                                          engine='cfgrib',
                                          backend_kwargs={
                                              'filter_by_keys': {
                                                  'typeOfLevel':
                                                  'isobaricInhPa'
                                              },
                                              'errors': 'ignore'
                                          })

            ds_mean_sea = xr.load_dataset(gribfile1,
                                          engine='cfgrib',
                                          backend_kwargs={
                                              'filter_by_keys': {
                                                  'typeOfLevel': 'meanSea'
                                              },
                                              'errors': 'ignore'
                                          })

            ds_isobaric2 = xr.load_dataset(gribfile2,
                                           engine='cfgrib',
                                           backend_kwargs={
                                               'filter_by_keys': {
                                                   'typeOfLevel':
                                                   'isobaricInhPa'
                                               },
                                               'errors': 'ignore'
                                           })

            ds_mean_sea2 = xr.load_dataset(gribfile2,
                                           engine='cfgrib',
                                           backend_kwargs={
                                               'filter_by_keys': {
                                                   'typeOfLevel': 'meanSea'
                                               },
                                               'errors': 'ignore'
                                           })

            prmsl = np.mean(np.dstack((ds_mean_sea.prmsl, ds_mean_sea2.prmsl)),
                            axis=2)
            gh_500 = np.mean(np.dstack(
                (ds_isobaric.gh.sel(isobaricInhPa=500),
                 ds_isobaric2.gh.sel(isobaricInhPa=500))),
                             axis=2)

        levels = np.arange(930, 1050, 4)
        cont = ax.contour(ds_mean_sea.longitude,
                          ds_mean_sea.latitude,
                          prmsl / 100.,
                          linewidths=0.4,
                          colors='lightcoral',
                          transform=ccrs.PlateCarree(),
                          levels=levels)

        levels = np.arange(0, 900, 8)
        cont = ax.contour(ds_isobaric.longitude,
                          ds_isobaric.latitude,
                          gh_500 / 10.,
                          linewidths=0.4,
                          colors='k',
                          transform=ccrs.PlateCarree(),
                          levels=levels)

    scat = ax.scatter(
        release_sel[:, 1],
        release_sel[:, 2],
        s=2,
        c=release_sel[:, 3] / 1000.,
        cmap='plasma',
        vmin=0.1,
        vmax=6.0,
        zorder=5,
        #transform=ccrs.Geodetic())
        transform=ccrs.PlateCarree())

    ax.scatter(
        meta['lat_lon_bounds'][0],
        meta['lat_lon_bounds'][1],
        s=14,
        marker='^',
        c='tab:red',
        zorder=3,
        #transform=ccrs.Geodetic())
        transform=ccrs.PlateCarree())

    cbar = fig.colorbar(scat, fraction=0.025, pad=0.01)

    cbar.ax.set_ylabel('Height [km]', fontweight='semibold', fontsize=12)
    cbar.ax.tick_params(axis='both',
                        which='major',
                        labelsize=12,
                        width=2,
                        length=4)

    # add the geometry boundaries...
    #     k = kml.KML()
    #     geo_bounds_file = '../../trace_pub/trace/data/geo_names_arctic.kml'
    #     with open(geo_bounds_file) as f:
    #         k.from_string(bytes(bytearray(f.read(), encoding='utf-8')))
    #     docu = list(k.features())[0]
    #     polygons = {}
    #     colors = [(0.65098039215686276, 0.84705882352941175, 0.32941176470588235, 1.0),
    #               (1.0, 0.85098039215686272, 0.18431372549019609, 1.0),
    #               (0.89803921568627454, 0.7686274509803922, 0.58039215686274515, 1.0),
    #               (0.40000000000000002, 0.76078431372549016, 0.6470588235294118, 1.0),
    #               (0.9882352941176471, 0.55294117647058827, 0.3843137254901961, 1.0),
    #               (0.55294117647058827, 0.62745098039215685, 0.79607843137254897, 1.0),
    #               (0.70196078431372544, 0.70196078431372544, 0.70196078431372544, 1.0)]
    #     for p in list(docu.features()):
    #         print(p.name)
    #         #print(p.geometry)
    #         polygons[p.name] = p.geometry
    #     for i, (name, poly) in enumerate(list(polygons.items())):
    #         print(i, name)
    #         #ax.add_geometries([poly], ccrs.Geodetic(), alpha=0.5, facecolor=colors[i])
    #         ax.add_geometries([poly], ccrs.Geodetic(), edgecolor=colors[i], facecolor='none', lw=3)

    ax.gridlines(linestyle=':')
    #ax.set_extent([-100, 80, 10, 80], crs=ccrs.PlateCarree())
    ##ax.set_extent([-70, 50, 20, 55], crs=ccrs.PlateCarree())
    ##ax.set_extent([-50, 40, 20, 55], crs=ccrs.PlateCarree())
    ##ax.set_extent([20, 50, 20, 40], crs=ccrs.PlateCarree())
    ##ax.set_extent([25, 35, 30, 40], crs=ccrs.PlateCarree())
    # North Pole
    #ax.set_extent([-180, 180, 45, 90], crs=ccrs.PlateCarree())

    # if maptype == 'northpole':
    #     ax.set_extent([-179, 179, 45, 90], crs=ccrs.PlateCarree())
    # elif maptype == 'southernocean':
    #     ax.set_extent([-179, 179, -75, -10], crs=ccrs.PlateCarree())
    if add_fire and 'M6' in add_fire:
        str1_pos = (.15, 0.080)
        str2_pos = (.15, 0.040)
    else:
        str1_pos = (.2, 0.080)

    ax.annotate(
        "MODIS land cover classification [Broxton and Zeng 2014, JAMC]",
        #xy=(.15, 0.108), xycoords='figure fraction',
        xy=str1_pos,
        xycoords='figure fraction',
        #xy=(.2, 0.085), xycoords='figure fraction',
        horizontalalignment='left',
        verticalalignment='bottom',
        fontsize=11)
    if add_fire and 'M6' in add_fire:
        ax.annotate(
            "MODIS Active Fire Product, FRP > 12 MW/pixel [DOI:10.5067/FIRMS/MODIS/MCD14DL.NRT.006]",
            #xy=(.15, 0.040), xycoords='figure fraction',
            xy=str2_pos,
            xycoords='figure fraction',
            horizontalalignment='left',
            verticalalignment='bottom',
            fontsize=11)
    #ax.annotate("VIIRS Active Fire Product, FRP > 4 MW/pixel [DOI:10.5067/FIRMS/VIIRS/VNP14IMGT.NRT.001]",
    #        xy=(.2, 0.065), xycoords='figure fraction',
    #        horizontalalignment='left', verticalalignment='bottom',
    #        fontsize=11)

    fig.legend(handles,
               labels,
               ncol=4,
               fontsize=10,
               bbox_to_anchor=(0.20, 0.185),
               loc='upper left')

    ax.set_title(
        'Flexpart particle positions {}UTC\nRelease: [{:.2f} {:.2f} {:.2f} {:.2f}] {:.0f}-{:.0f}m'
        .format(dt.strftime('%Y-%m-%d %H'), *meta['lat_lon_bounds'],
                *meta['heights']),
        fontweight='semibold',
        fontsize=13)

    #fig.patch.set_facecolor('xkcd:mint green')
    #bd = matplotlib.path.Path([[0,0],[1,0],[0.5,0.5],[0,1],[0,0]])
    #ax.set_boundary(bd, transform=ax.transAxes)

    savename = savepath + "/" + "r{:0>2}_{}_{:.0f}_trajectories_map.png".format(
        release_no, dt.strftime("%Y%m%d_%H"), np.mean(meta['heights']))
    print(savename)
    fig.savefig(savename, dpi=180, transparent=False)
    plt.close('all')
예제 #18
0
dx = 0.0416666666666; dy = 0.0416666666666
lon_4km, lat_4km = np.meshgrid(np.arange(lonlim[0], lonlim[1]+dx, dx), np.arange(latlim[0], latlim[1]+dy, dy))

import shapely
import cartopy.io.shapereader as shpreader
from cartopy.io.shapereader import Reader

shpfilename = shpreader.natural_earth(resolution='110m', category='physical', name='ocean')
land_shp = Reader(shpfilename)

shape_4km = lon_4km.shape
land_id = np.ones(shape_4km)*np.nan
for i in range(shape_4km[0]):
    for j in range(shape_4km[1]):
        temp_point = shapely.geometry.Point(lon_4km[i, j], lat_4km[i, j])
        for n, shp in enumerate(land_shp.records()):
            if shp.geometry.contains(temp_point):
                land_id[i, j] = n

land_mask = ~np.isnan(land_id)

# ETOPO interp
print('Process ETOPO')
with nc.Dataset(BACKUP_dir+'ETOPO1_Ice_g_gmt4.grd') as nc_obj:
    etopo_x = nc_obj.variables['x'][2000:] # subsetting north america
    etopo_y = nc_obj.variables['y'][2000:]
    etopo_z = nc_obj.variables['z'][2000:, 2000:]
etopo_lon, etopo_lat = np.meshgrid(etopo_x, etopo_y)

etopo_4km    = du.interp2d_wraper(etopo_lon, etopo_lat, etopo_z, lon_4km, lat_4km, method=interp_method)
etopo_025    = du.interp2d_wraper(etopo_lon, etopo_lat, etopo_z, lon_025, lat_025, method=interp_method)
예제 #19
0
    else:
        background_image['alpha'] = 1.0

    #Draw geography
    m.drawstates()
    m.drawcoastlines()
    m.drawcountries()
    print("--> Plotted geographic & political boundaries")

    #========================================================================================================
    # Plot data
    #========================================================================================================

    #Iterate through all states
    total_cases = 0
    for record, state in zip(shp.records(), shp.geometries()):

        #Reference state name as a separate variable
        name = record.attributes['NAME']

        #Get state's case data for this date
        if name.lower() in cases.keys():
            idx = cases[name.lower()]['date'].index(plot_start_date)
            if plot_type not in [
                    'confirmed', 'confirmed_normalized', 'deaths', 'recovered',
                    'active', 'daily'
            ]:
                plot_type = 'confirmed'
            case_number = cases[name.lower()][plot_type][idx]
            total_cases += case_number
        else:
예제 #20
0
                  ccrs.PlateCarree(),
                  facecolor="None",
                  edgecolor='black')
# -

# To make a choropleth, we simply need to set the `facecolor` of each geometry. First, let's read in some county-level data that we can plot.

import pandas as pd
election_df = pd.read_csv(
    "https://raw.githubusercontent.com/dlsun/data-science-book/"
    "master/data/election2016.csv")
election_df

# We need to merge this data with the shapefile that we just loaded. We can create a `DataFrame` out of the `records` of a shapefile.

shp_df = pd.DataFrame([record.attributes for record in shp.records()])
shp_df

# We will need to merge `election_df` with `shp_df`. But what do we merge the `DataFrame`s on? It turns out that every county in the United States is assigned a unique ID called a FIPS code. The FIPS code appears in `election_df` as `combined_fips` and in `shp_df` as `GEOID`. Let's take a look at these columns.

election_df.combined_fips

shp_df.GEOID

# Notice that `shp_df` treats the FIPS code as a string (so every FIPS code is exactly 5 digits, with a leading zero if necessary). On the other hand, `election_df` treats the FIPS code as an integer. If we want to join the two, we will have to cast them to the same type. It is probably easier to convert the string to an integer than vice versa.

shp_df["GEOID"] = shp_df["GEOID"].astype(int)

# Now we are ready to merge the two `DataFrame`s.

all_data = shp_df.merge(election_df,
import os

plt.clf()

#ax = geo_plots.add_map(bbox=(-89,-85,27.5,31))
ax = geo_plots.add_map(bbox=(-90, -84, 27.5, 31))
#land_10m = cfeature.NaturalEarthFeature('physical','land','50m',\
#    edgecolor='face',facecolor='0.75')
##ax.add_feature(cfeature.LAND, facecolor='0.75')
#ax.add_feature(land_10m)
#if bbox not specified, this will use map bounds from bna

bathy_file = os.path.join('gom_bathy', 'Bathymetry.shp')
bathy = Reader(bathy_file)

for rec, geo in zip(bathy.records(), bathy.geometries()):
    if rec.attributes['DEPTH_METR'] in ['100m', '500m', '1000m']:
        shape_feature = ShapelyFeature(geo,
                                       ccrs.PlateCarree(),
                                       facecolor='none')
        ax.add_feature(shape_feature)

#add particles at one time
t = datetime.datetime(2016, 9, 21, 1)

filename = 'gulf_tamoc.nc'
ax = geo_plots.contour_particles(ax, filename, t, levels=[0.1, 0.4, 0.6, 1])
#ax = geo_plots.plot_particles(ax,filename,t,depth=0,color='b')

#add initial location
예제 #22
0
def map_depart_from_normal_temps(date_start, date_end, begin_normal_year, 
                                 end_normal_year,email, how='stcd', legend=False,savepath=False):
    fig = plt.figure(figsize=FIG_SIZE)
    ax = plt.axes(projection=ccrs.LambertConformal())
    ax.set_extent([-124.5,-64,21.3,49], ccrs.Geodetic())
    plt.margins(0,0)
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    reader_state = Reader(STATE_SHAPEFILE_PATH+STATE_SHAPEFILE_FNAME)
    reader_how = Reader(ATTRIBUTE_DICT[how][1])
    dfn_temps = ncep_util.depart_from_normal_temps(date_start, date_end, begin_normal_year, 
                                                   end_normal_year,email,how=how)
    dfn = pd.DataFrame(dfn_temps.mean(skipna=True).round()).T.astype(int)
    for record in reader_how.records():
        if record.attributes[ATTRIBUTE_DICT[how][0]] in dfn.columns:
            val = dfn[record.attributes[ATTRIBUTE_DICT[how][0]]].values.astype(int)[0]
            if val < 0:
                color_palette_modified = [x for x in color_palette.keys() if x > val]
                facecolor = color_palette[min(color_palette_modified)]
            if val > 0:
                color_palette_modified = [x for x in color_palette.keys() if x < val]
                facecolor = color_palette[max(color_palette_modified)]
            if val < eps and val > -eps:
                facecolor = color_palette[0]
            ax.add_geometries(record.geometry,ccrs.PlateCarree(),facecolor=facecolor,
                              edgecolor=facecolor,linewidth=0.4)
    for record in reader_state.records():
        ax.add_geometries(record.geometry,ccrs.PlateCarree(),facecolor='none',
                          edgecolor='white',linewidth=0.5)
    ax.outline_patch.set_edgecolor('white')    
    if legend:
        inc = 0.2
        y = list(set([float(x) for x in color_palette.keys()]))
        y.sort()
        for color in y:
            rect = mpatches.Rectangle(xy=(0.85,inc), width=0.025, height=0.05,
                                            facecolor=color_palette[color],
                                            transform = ax.transAxes)
            ax.add_patch(rect)
            if color < 0:   
                if int(color)==int(min(y)):
                    plt.annotate(str(int(color))+' or below',xy=(0,0),xytext=(0.875,inc+0.005),
                                 textcoords='axes fraction',fontname='Arial',fontsize=9,
                             color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)                 
                elif int(color)==0:
                    plt.annotate(' '+str(int(color))+' to '+str(int(color-5)),xy=(0,0),
                                 xytext=(0.875,inc+0.005),textcoords='axes fraction',fontname='Arial',fontsize=9,
                             color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)    
                else:                    
                    plt.annotate(str(int(color))+' to '+str(int(color-5)),xy=(0,0),
                                 xytext=(0.875,inc+0.005),textcoords='axes fraction',fontname='Arial',fontsize=9,
                             color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)
            elif color > 0:
                if int(color)==int(max(y)):
                    plt.annotate(' '+str(int(color))+' or above',xy=(0,0),xytext=(0.875,inc+0.005),
                                 textcoords='axes fraction',fontname='Arial',fontsize=9,
                             color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)                      
    
                else:
                    plt.annotate(' '+str(int(color))+' to '+str(int(color+5)),xy=(0,0),
                                 xytext=(0.875,inc+0.005),textcoords='axes fraction',fontname='Arial',fontsize=9,
                        color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)     
            else:
                plt.annotate(' '+str(int(color)),xy=(0,0),xytext=(0.875,inc+0.005),textcoords='axes fraction',
                             fontname='Arial',fontsize=9,
                         color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)                          
            inc+=0.05
        plt.annotate('degrees\nFahrenheit',xy=(0,0), xytext = (0.85,inc+0.075),textcoords='axes fraction',
                     fontname='Arial',fontsize=9,
                    color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)
        plt.annotate('above/below',xy=(0,0),xytext = (0.85,inc+.02),textcoords='axes fraction',fontname='Arial',
                     fontsize=9,
                    color=(100/255.0,100/255.0,100/255.0),transform = ax.transAxes)         
    if savepath:
        dfn.to_csv(savepath+'.csv')
        fig.savefig(savepath+".png",bbox_inches='tight',transparent=True)
    return plt  
예제 #23
0
region = [70,140,15,60]
ax.set_extent(region,crs = proj)

#经纬度刻度线方法
ax.set_xticks(np.arange(70,130+10,20),crs = proj)
ax.set_yticks(np.arange(15,60+5,10),crs=proj)
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.tick_params(labelsize=15)

contourf = ax.contourf(lon,lat,u1_avg,lev,cmap='Blues',transform=proj,extend='both')

countries = shp.records()
cn_multipoly, = [country.geometry for country in countries
                 if country.attributes['CNTRY_NAME'] == 'China']  # 选择地图属性下'NAME'属性里名字是'China'的一条多边形

paths = []
for i in range(len(cn_multipoly)):
    cn_geom, = geos_to_path(cn_multipoly.geoms[i])
    paths.append(cn_geom)

path = Path.make_compound_path(*paths)
for collection in contourf.collections:
    collection.set_clip_path(path, proj._as_mpl_transform(ax))

# 白化刻度
# contour = ax.contour(lon,lat,u1_avg,lev,cmap='Blues',transform=proj,extend='both')
# cn_label = plt.clabel(contour,inline=1,fontsize=10,fmt="%.fr")
예제 #24
0
        scale="10m",
        facecolor="none",
        name='coastline',
    )
    land = NaturalEarthFeature(
        category="physical",
        scale="10m",
        #facecolor=feature.COLORS['land'],
        facecolor='lightgray',
        name='land',
    )
    fname = 'files/ne_10m_populated_places.shp'
    reader = Reader(fname)
    #city names
    city = []
    for i, record in enumerate(reader.records()):
        name = record.attributes['name_es']
        geometry = record.geometry
        x, y = geometry.centroid.x, geometry.centroid.y
        if all([lon_min < x < lon_max, lat_min < y < lat_max]):
            city.append([x, y, name])
#city points
    points = [list(point.coords) for point in reader.geometries()]
    xp = [
        point[0][0] for point in points if all(
            [lon_min < point[0][0] < lon_max, lat_min < point[0][1] < lat_max])
    ]
    yp = [
        point[0][1] for point in points if all(
            [lon_min < point[0][0] < lon_max, lat_min < point[0][1] < lat_max])
    ]