Beispiel #1
0
 def drawcity(self, lw=None, color=None):
     lw = self.linewidth['city'] if lw is None else lw
     color = self.linecolor['city'] if color is None else color
     self.ax.add_feature(cfeature.ShapelyFeature(ciosr.Reader(_CityDir).geometries(),
         ccrs.PlateCarree(), facecolor='none', edgecolor=color), linewidth=lw)
     self.ax.add_feature(cfeature.ShapelyFeature(ciosr.Reader(_CityTWDir).geometries(),
         ccrs.PlateCarree(), facecolor='none', edgecolor=color), linewidth=lw)
def createMap():
    reader = shpreader.Reader(
        '/Users/Sainayan/Downloads/countyl010g_shp_nt00964/countyl010g.shp')
    reader2 = shpreader.Reader(
        '/Users/Sainayan/Downloads/statesp010g.shp_nt00938/statesp010g.shp')
    counties = list(reader.geometries())
    states = list(reader2.geometries())
    COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())
    STATES = cfeature.ShapelyFeature(states, ccrs.PlateCarree())

    plt.figure(figsize=(10, 6))
    ax = plt.axes(projection=ccrs.PlateCarree())

    source = 'nationalmap.gov'
    ax.add_feature(cfeature.LAND.with_scale('50m'))
    ax.add_feature(cfeature.OCEAN.with_scale('50m'))
    ax.add_feature(cfeature.LAKES.with_scale('50m'))
    #ax.add_feature(cfeature.RIVERS.with_scale('50m'),edgecolor='black')
    ax.add_feature(COUNTIES, facecolor='none', edgecolor='gray')
    ax.add_feature(STATES, facecolor='none', edgecolor='black')
    #stext = AnchoredText('Source: {}'' '.format(source), loc=4, prop={'size': 12}, frameon=True)
    ax.coastlines('50m')
    #ax.add_artists(stext)

    ax.set_extent([-83, -65, 33, 44])
    plt.show()
def main():
    lat, lon, radius = -66.10165712, 136.51515176, 55.957758952975269
    filename = 'Torres-Strait.png'
    land = earth.ReadShapes('shapes/ne_10m_land')
    klass = crs.AzimuthalEquidistant
    proj, land_projected = earth.Project(lat, lon, land, klass)
    circle = earth.Circle(lat, lon, radius, proj)

    pyplot.figure(figsize=(6, 6))
    ax = pyplot.axes(projection=proj)
    ax.set_extent([123, 153, -32, 0])
    land_feature = feature.ShapelyFeature(land_projected,
                                          proj,
                                          edgecolor='none',
                                          facecolor='black')
    circle_feature = feature.ShapelyFeature([circle],
                                            proj,
                                            linewidth=1,
                                            edgecolor='blue',
                                            facecolor='none')
    intersection_feature = feature.ShapelyFeature(
        [g.intersection(circle) for g in land_projected],
        proj,
        linewidth=1,
        edgecolor='yellow',
        facecolor='none')
    ax.add_feature(land_feature)
    ax.add_feature(circle_feature)
    ax.add_feature(intersection_feature)
    ax.gridlines(edgecolor='#bbbbbb', linestyle='-', linewidth=0.5)
    pyplot.savefig(filename, bbox_inches='tight', pad_inches=0.2)
Beispiel #4
0
def add_map_features(ax, counties=None, roads=None):
    """
    """
    ax.add_feature(cfeat.COASTLINE.with_scale('10m'))
    ax.add_feature(cfeat.BORDERS.with_scale('10m'))

    # Slightly transparent rivers
    ax.add_feature(cfeat.RIVERS.with_scale('10m'),
                   alpha=0.75,
                   edgecolor='aqua')

    # Dotted lines for state borders
    ax.add_feature(cfeat.STATES.with_scale('10m'),
                   linestyle=":",
                   edgecolor='black')

    if counties is not None:
        countfeat = cfeat.ShapelyFeature(counties, ccrs.PlateCarree())
        ax.add_feature(countfeat,
                       facecolor='none',
                       edgecolor='#ff0092',
                       alpha=0.25)

    if roads is not None:
        # Reminder that roads is a dict with keys:
        #  interstates, fedroads, stateroads, otherroads
        for rtype in roads:
            good = True
            if rtype == "Interstate":
                rcolor = 'gold'
                ralpha = 0.55
            elif rtype == "Federal":
                rcolor = 'gold'
                ralpha = 0.55
            elif rtype == 'State':
                rcolor = 'LightSkyBlue'
                ralpha = 0.55
            elif rtype == "Other":
                rcolor = 'LightSkyBlue'
                ralpha = 0.45
            else:
                good = False

            # Only plot the ones specifed above; if it doesn't fit one of
            #   those categories then skip it completely because something
            #   is wrong or changed.
            if good is True:
                sfeat = cfeat.ShapelyFeature(roads[rtype], ccrs.PlateCarree())
                ax.add_feature(sfeat,
                               facecolor='none',
                               edgecolor=rcolor,
                               alpha=ralpha)

    return ax
Beispiel #5
0
def png_db(C, composite_img, DATE):
    # Satellite height
    sat_h = C['goes_imager_projection'].perspective_point_height

    # Satellite longitude
    sat_lon = C['goes_imager_projection'].longitude_of_projection_origin

    # Satellite sweep
    sat_sweep = C['goes_imager_projection'].sweep_angle_axis

    x = C['x'].values * sat_h
    y = C['y'].values * sat_h

    # Create a pyproj geostationary map object
    p = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep)

    # Perform cartographic transformation. That is, convert image projection coordinates (x and y)
    # to latitude and longitude values.
    XX, YY = np.meshgrid(x, y)
    lons, lats = p(XX, YY, inverse=True)

    plt.figure(figsize=[15, 12])
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.set_extent([-125, -113, 33, 43], ccrs.PlateCarree())

    plt.title('GOES-17 True Color',
              loc='left',
              fontweight='semibold',
              fontsize=15)
    plt.title('%s' % DATE.strftime('%d %B %Y %H:%M UTC '), loc='right')

    # We need an array the shape of the data, so use R. The color of each pixel will be set by color=colorTuple.
    plt.pcolormesh(lons,
                   lats,
                   composite_img['R'],
                   color=composite_img['rgb_composite'],
                   transform=ccrs.PlateCarree())

    shp_path = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', 'static', 'images',
                     'countyl010g_shp', 'countyl010g.shp'))

    reader = shpreader.Reader(shp_path)
    countiesShp = list(reader.geometries())
    COUNTIES = cfeature.ShapelyFeature(countiesShp, ccrs.PlateCarree())
    ax.add_feature(COUNTIES,
                   facecolor='none',
                   edgecolor='white',
                   linewidth=0.25)

    buf = io.BytesIO()
    plt.savefig(buf, bbox_inches='tight', format='png')
    #plt.savefig('testout.png', bbox_inches='tight', format='png')
    #plt.show()
    buf.seek(0)

    ablob = buf.getvalue()
    plt.close()
    buf.close()
    return ablob
Beispiel #6
0
def tissot(rads_km=None, lons=None, lats=None, n_samples=80, globe=None, ax=None, draw=False, **kwargs):
    import numpy as np
    import cartopy.crs as ccrs
    import cartopy.feature as feature
    import shapely.geometry as sgeom
    from cartopy import geodesic
    import cartopy.mpl.patch as cpatch

    geod = geodesic.Geodesic(radius=globe.semimajor_axis, flattening=globe.flattening)
    geoms = []

    rads_km = np.asarray(rads_km)
    lons = np.asarray(lons)
    lats = np.asarray(lats)

    for i in range(len(lons)):
        circle = geod.circle(lons[i], lats[i], rads_km[i],
                             n_samples=n_samples)
        geoms.append(sgeom.Polygon(circle))

    polys = cpatch.geos_to_path(geoms)

    if draw:
        if ax==None: ax = plt.gca()
        f = feature.ShapelyFeature(geoms, ccrs.Geodetic(globe=globe),
                                       **kwargs)
        ax.add_feature(f)

    return polys
Beispiel #7
0
    def land(self, facecolor="white", **kwargs):
        """
        Draw the GIS coastline data from the state of Hawaii to draw the
        land boundaries. This does not include rivers, etc., only the
        coastline.

        Parameters
        ----------
        color: string, optional
            Color to draw the land mask with
        **kwargs:
            Additional arguments to add_feature

        Returns
        -------
        None

        """
        _shape_file = os.path.dirname(__file__) + "/hawaii_coast/hawaii.shp"

        if not hasattr(self, "feature"):
            self.feature = cft.ShapelyFeature(
                cartopy.io.shapereader.Reader(_shape_file).geometries(),
                self.proj())

        # Draw the loaded shapes
        self.ax.add_feature(self.feature, facecolor=facecolor, **kwargs)
Beispiel #8
0
 def drawprovince(self, lw=None, color=None):
     lw = self.linewidth['province'] if lw is None else lw
     color = self.linecolor['province'] if color is None else color
     if self.mapset and self.mapset.province:
         self.usefeature(self.mapset.province, edgecolor=color, facecolor='none',
             linewidth=lw)
     else:
         self.ax.add_feature(cfeature.ShapelyFeature(
             ciosr.Reader(_ProvinceDir).geometries(), ccrs.PlateCarree(),
             facecolor='none', edgecolor=color), linewidth=lw)
Beispiel #9
0
def create_map(extent, xstep, ystep):
    # 加载shp
    shp_path_p = '/Users/wangyucheng/Desktop/kuihua/Province_9/'
    shp_path_c = '/Users/wangyucheng/Desktop/kuihua/diqujie/'
    # --创建画图空间
    proj = ccrs.PlateCarree()  # 创建坐标系
    fig = plt.figure(figsize=(8, 10))  # 创建页面
    ax = plt.axes(projection=ccrs.PlateCarree())

    # --设置地图属性
    reader_p = Reader(shp_path_p + 'Province_9.shp')
    province = cfeat.ShapelyFeature(reader_p.geometries(),
                                    proj,
                                    edgecolor='k',
                                    facecolor='none')
    reader_c = Reader(shp_path_c + 'diquJie_polyline.shp')
    city = cfeat.ShapelyFeature(reader_c.geometries(),
                                proj,
                                edgecolor='k',
                                facecolor='none')
    # 加载省界线
    ax.add_feature(province)
    # 加载市界
    ax.add_feature(city)
    # 加载经纬范围
    ax.set_extent(extent, crs=proj)
    # --设置网格点属性
    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=1.2,
                      color='k',
                      alpha=0.5,
                      linestyle='--')
    gl.xlabels_top = False  # 关闭顶端的经纬度标签
    gl.ylabels_right = False  # 关闭右侧的经纬度标签
    gl.xformatter = LONGITUDE_FORMATTER  # x轴设为经度的格式
    gl.yformatter = LATITUDE_FORMATTER  # y轴设为纬度的格式
    gl.xlocator = mticker.FixedLocator(
        np.arange(extent[0], extent[1] + xstep, xstep))
    gl.ylocator = mticker.FixedLocator(
        np.arange(extent[2], extent[3] + ystep, ystep))
    return fig, ax
Beispiel #10
0
def create_map(fig):
    shp_path = r'/mnt/e/公众号/可视化/cartopy/China_shp_lqy/'
    # --创建画图空间
    proj = ccrs.LambertConformal(central_longitude=110,
                                 central_latitude=35,
                                 standard_parallels=(30, 60))  # 创建坐标系

    ax = fig.subplots(1, 1, subplot_kw={'projection': proj})
    # --设置shp
    provinces = cfeat.ShapelyFeature(
        Reader(shp_path + 'province.shp').geometries(),
        ccrs.PlateCarree(),
        edgecolor='k',
        facecolor='none',
    )
    ax.add_feature(provinces, linewidth=0.6, zorder=2)
    # --设置范围
    ax.set_extent([80, 135, 15, 55], crs=ccrs.PlateCarree())
    # --关闭边框
    ax.spines['geo'].set_visible(False)
    # --设置刻度
    ax.tick_params(axis='both',
                   labelsize=5,
                   direction='out',
                   labelbottom=False,
                   labeltop=False,
                   labelleft=False,
                   labelright=False)
    # --设置小地图
    left, bottom, width, height = 0.675, 0.13, 0.23, 0.27
    ax2 = fig.add_axes([left, bottom, width, height],
                       projection=ccrs.PlateCarree())
    provinces = cfeat.ShapelyFeature(
        Reader(shp_path + 'province.shp').geometries(),
        ccrs.PlateCarree(),
        edgecolor='k',
        facecolor='gray',
    )
    ax2.add_feature(provinces, linewidth=0.6, zorder=2)
    ax2.set_extent([105, 125, 0, 25], crs=ccrs.PlateCarree())
    return ax
Beispiel #11
0
def _PlotComparisonMap(tensor_info, segments, point_sources, input_model,
                       solution):
    """We plot slip map.
    """
    input_slip = input_model['slip']
    plane_info = segments[0]
    stk_subfaults, dip_subfaults, delta_strike, delta_dip, hyp_stk, hyp_dip\
        = pl_mng.__unpack_plane_data(plane_info)
    if stk_subfaults * dip_subfaults == 1:
        return
    slip = solution['slip']
#
# accurate plot coordinates
#
    segments_lats, segments_lons = __redefine_lat_lon(segments, point_sources)

    margin = min(1.5 * (stk_subfaults * delta_strike) / 111.19, 10)#3
    lat0 = tensor_info['lat']
    lon0 = tensor_info['lon']
    margins = [lon0 - margin, lon0 + margin, lat0 - margin, lat0 + margin]
    dictn = {'projection': ccrs.PlateCarree(), 'facecolor': '#eafff5'}
    shpfilename = shpreader.natural_earth(
        resolution='10m', category='cultural', name='admin_0_countries')
    countries = cf.ShapelyFeature(
        shpreader.Reader(shpfilename).geometries(), ccrs.PlateCarree(),
        edgecolor='black', facecolor='lightgray')

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(30, 15), subplot_kw=dictn)
    ax1.set_title('Inverted model', fontsize=22)
    ax2.set_title('Original model', fontsize=22)
    fig.subplots_adjust(hspace=0, wspace=0.1, top=0.9, bottom=0.3)
    for ax in [ax1, ax2]:
        ax = set_map_cartopy(ax, margins, countries=countries)
        ax.plot(lon0, lat0, 'w*', markersize=15, transform=ccrs.PlateCarree(),
            zorder=4)
    max_slip = max([np.amax(slip_fault) for slip_fault in slip])
    max_slip2 = max([np.amax(input_slip2) for input_slip2 in input_slip])
    max_slip = max(max_slip, max_slip2)
#
# plot slip map
#
    ax1, cs1 = plot_map(ax1, segments_lats, segments_lons, slip, max_val=max_slip,
                       transform=dictn['projection'])
    ax2, cs2 = plot_map(ax2, segments_lats, segments_lons, input_slip,
                        max_val=max_slip, transform=dictn['projection'])
    fig.subplots_adjust(bottom=0.15)
    cbar_ax = fig.add_axes([0.1, 0.05, 0.8, 0.05])
    cb = fig.colorbar(cs2, cax=cbar_ax, orientation='horizontal')
    cb.set_label('Slip (cm)')
    plt.savefig('Comparison.png', bbox_inches='tight')
    plt.close()
    return
Beispiel #12
0
 def map(self):
     shp_path = '/home/qxs/bma/shp/cn_shp/'
     # --创建画图空间
     proj = ccrs.PlateCarree()  # 创建坐标系
     fig = plt.figure(figsize=(6, 8), dpi=400)  # 创建页面
     ax = fig.subplots(1, 1, subplot_kw={'projection': proj})  # 创建子图
     # --设置地图属性
     borders = cfeat.ShapelyFeature(Reader(shp_path +
                                           'cntry02.shp').geometries(),
                                    proj,
                                    edgecolor='k',
                                    facecolor=cfeat.COLORS['land'])
     provinces = cfeat.ShapelyFeature(Reader(shp_path +
                                             'bou2_4l.shp').geometries(),
                                      proj,
                                      edgecolor='k',
                                      facecolor=cfeat.COLORS['land'])
     # ax.add_feature(provinces, linewidth=0.6, zorder=2)
     ax.add_feature(borders, linewidth=0.6, zorder=10)
     ax.add_feature(cfeat.COASTLINE.with_scale('50m'),
                    linewidth=0.6,
                    zorder=10)  # 加载分辨率为50的海岸线
     # ax.add_feature(cfeat.RIVERS.with_scale('50m'), zorder=10)  # 加载分辨率为50的河流
     # ax.add_feature(cfeat.LAKES.with_scale('50m'), zorder=10)  # 加载分辨率为50的湖泊
     ax.set_extent([100, 131, 0, 42])
     # --设置网格点属性
     gl = ax.gridlines(crs=ccrs.PlateCarree(),
                       draw_labels=True,
                       linewidth=1.2,
                       color='k',
                       alpha=0.5,
                       linestyle='--')
     gl.xlabels_top = False  # 关闭顶端的经纬度标签
     gl.ylabels_right = False  # 关闭右侧的经纬度标签
     gl.xformatter = LONGITUDE_FORMATTER  # x轴设为经度的格式
     gl.yformatter = LATITUDE_FORMATTER  # y轴设为纬度的格式
     gl.xlocator = mticker.FixedLocator(np.arange(95, 135 + 5, 5))
     gl.ylocator = mticker.FixedLocator(np.arange(-5, 45 + 5, 5))
     return ax
def main():
    lat, lon, radius = 50, 20, 90
    lands = earth.ReadShapes('shapes/ne_110m_land')
    proj, lands_projected = earth.Project(lat, lon, lands)
    pyplot.figure(figsize=(6, 6))
    ax = pyplot.axes(projection=proj)
    lands_feature = feature.ShapelyFeature(lands_projected,
                                           proj,
                                           edgecolor='none',
                                           facecolor='black')
    ax.add_feature(lands_feature)
    ax.gridlines(edgecolor='#bbbbbb', linestyle='-', linewidth=1)
    pyplot.savefig('Centre-in-Krakow.png', bbox_inches='tight')
Beispiel #14
0
def get_us_from_shapefile(border=False, simplify=None):
    shapefile_dir = join(
        cfg.root_dir,
        "data/raw/shapefiles/gadm36_USA_shp/gadm36_USA_0.shp",
    )
    rdr = shapereader.Reader(shapefile_dir)
    us = list(rdr.geometries())[0]
    if simplify is not None:
        us = us.simplify(simplify)
    if border:
        us_border = cfeature.ShapelyFeature(
            us, crs=ccrs.PlateCarree(), facecolor="None", edgecolor="k"
        )
        us = (us, us_border)
    return us
Beispiel #15
0
def create_STATES(us_states_location):
    """
    Create shapely files of states.
    
    Args:
        us_states_location (str): Directory location of states shapefiles.
    
    Returns:
        States data as cartopy feature for plotting.
    """
    proj = ccrs.LambertConformal(central_latitude=25,
                                 central_longitude=265,
                                 standard_parallels=(25, 25))
    reader = shpreader.Reader(
        f'{us_states_location}/ne_50m_admin_1_states_provinces_lines.shp')
    states = list(reader.geometries())
    STATES = cfeature.ShapelyFeature(states, ccrs.PlateCarree())
    return STATES
Beispiel #16
0
def load_counties(projection, resolution='500k'):
    """
    County Shapefiles from the Census Bureau (2017)
    https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html

    projection - The cartopy map projection
    resolution - '500k' is the highest resolution (default)
                 '5m'
                 '20m' is the lowest resolution
    """
    if platform.system() == 'Linux':
        source = '/uufs/chpc.utah.edu/common/home/u0553130/pyBKB_v3/BB_maps/shapefiles/cb_2017_us_county_%s/cb_2017_us_county_%s.shp' % (
            resolution, resolution)
    else:
        source = 'C:\\Users\\blaylockbk\\OneDrive\\Documents\\pyBKB_v3\\BB_maps\\shapefiles\\cb_2017_us_county_%s\\cb_2017_us_county_%s.shp' % (
            resolution, resolution)
    return cfeature.ShapelyFeature(Reader(source).geometries(),
                                   projection,
                                   facecolor='none')
def show_map():
    #reader = shpreader.Reader('shapefiles/countyp020.shp')
    reader = shpreader.Reader('shapefiles/cgd114p010g.shp')
    counties = list(reader.geometries())

    COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())

    plt.figure(figsize=(20, 12))
    ax = plt.axes(projection=ccrs.PlateCarree())

    ax.add_feature(cfeature.LAND.with_scale('50m'))
    ax.add_feature(cfeature.OCEAN.with_scale('50m'))
    ax.add_feature(cfeature.LAKES.with_scale('50m'))
    ax.add_feature(cfeature.STATES.with_scale('50m'))
    ax.add_feature(COUNTIES, facecolor='none', edgecolor='gray')

    ax.coastlines('50m')

    ax.set_extent([-125, -65, 25, 47])
    plt.show()
def get_checkerboard_geoms(delta, us, minx, miny, maxx, maxy):
    b = miny
    l = minx
    t = b + delta
    r = l + delta

    cells = []
    col = 0
    row = 0

    while (r < maxx) or (t < maxy):
        ctr = col + row
        if ctr % 2:
            fc = "k"
        else:
            fc = "w"
        geom = shp.geometry.box(l, b, r, t).intersection(us)
        if geom.bounds != ():
            cells.append(
                cfeature.ShapelyFeature(
                    [geom],
                    facecolor=fc,
                    edgecolor=None,
                    linewidth=0,
                    crs=ccrs.PlateCarree(),
                )
            )
        l = r
        col += 1

        if l >= maxx:
            l = minx
            b = t
            row += 1
            col = 0

        t = b + delta
        r = l + delta

    return cells
Beispiel #19
0
def show():
    cwd = os.getcwd()
    root = plib.Path(cwd).parents[1]

    coords_path = os.path.join(root, 'data', 'raw',
                               'massachusetts_cities_coords.csv')
    coords = mfetch.get_data(coords_path)

    x = coords['Latitude'].values
    y = coords['Longitude'].values

    request = cimgt.OSM()
    fig, ax = plt.subplots(figsize=(10, 16),
                           subplot_kw=dict(projection=request.crs))

    ax.set_extent([-73.41, -69.93, 41.21, 42.92])
    ax.add_image(request, 8)

    county_shape = os.path.join(root, 'data', 'maps', 'county',
                                'countyl010g.shp')
    county_reader = cshp.Reader(county_shape)
    counties = list(county_reader.geometries())
    county_features = cfeat.ShapelyFeature(counties, ccrs.PlateCarree())
    ax.add_feature(county_features, facecolor='none', edgecolor='gray')
    ax.set_title('LEED Buildings in Massachusetts')

    plt.plot(x,
             y,
             color='red',
             linewidth=0,
             marker='o',
             transform=ccrs.Geodetic(),
             label='LEED-Certified Building')

    ax.legend()

    plt.show()
Beispiel #20
0
def main():
    download_dataset()

    parser = argparse.ArgumentParser()
    parser.add_argument('-m',
                        '--map',
                        help='Which type of map to be generated.')
    args = parser.parse_args()

    if args.map == 'verywide':
        map_ = map_utils.VeryWide()
    elif args.map == 'regional':
        map_ = map_utils.Regional()
    elif args.map == 'local':
        map_ = map_utils.Local()
    else:
        print("Invalid Map Type Requested.")
        return

    # Open dataset
    file = '../output/DHLPCoR_data.grb2'
    data = pygrib.open(file)

    # Grab the keys from the data we want
    maximum_temperatures = data.select(name='Maximum temperature')
    minimum_temperatures = data.select(name='Minimum temperature')
    percent_chance_rain = data.select(
        name='Probability of 0.01 inch of precipitation (POP)')

    # loops Day by day (1-5)
    day = 1
    for max_temperatures, min_temperatures, percent_chance_rains in zip(
            maximum_temperatures, minimum_temperatures, percent_chance_rain):
        # Max Temperature data
        max_temperature_data = []
        max_temp_latitudes, max_temp_longitudes = max_temperatures.latlons()
        max_temp_values = max_temperatures.values
        for latitudes, longitudes, values in zip(max_temp_latitudes,
                                                 max_temp_longitudes,
                                                 max_temp_values):
            for lat, lon, value in zip(latitudes, longitudes, values):
                max_temperature_data.append({
                    'lat': lat,
                    'lon': lon,
                    'value': value
                })

        # Min Temperature data
        min_temperature_data = []
        min_temp_lats, min_temp_lons = min_temperatures.latlons()
        min_temp_values = min_temperatures.values
        for latitudes, longitudes, values in zip(min_temp_lats, min_temp_lons,
                                                 min_temp_values):
            for lat, lon, value in zip(latitudes, longitudes, values):
                min_temperature_data.append({
                    'lat': lat,
                    'lon': lon,
                    'value': value
                })

        # Percent chance of rain data
        percent_chance_rain_data = []
        per_chance_rain_lats, per_chance_rain_lons = percent_chance_rains.latlons(
        )
        per_chance_rain_values = percent_chance_rains.values
        for latitudes, longitudes, values in zip(per_chance_rain_lats,
                                                 per_chance_rain_lons,
                                                 per_chance_rain_values):
            for lat, lon, value in zip(latitudes, longitudes, values):
                percent_chance_rain_data.append({
                    'lat': lat,
                    'lon': lon,
                    'value': value
                })

        # Create the figure for graphing
        fig = plt.figure(figsize=(15, 9))
        ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator())
        ax.set_extent(map_.NorthSouthEastWest[::-1], crs=ccrs.Geodetic())

        # Add boundaries to plot
        ax.add_feature(cfeature.OCEAN, facecolor=cfeature.COLORS['water'])
        if map_.map_type == 'verywide':
            ax.add_feature(cfeature.STATES.with_scale('50m'),
                           linewidth=0.5,
                           facecolor=cfeature.COLORS['land'])
        elif map_.map_type == 'regional' or map_.map_type == 'local':
            ax.add_feature(cfeature.STATES.with_scale('50m'),
                           linewidth=0.5,
                           facecolor=cfeature.COLORS['land'])
            reader = shpreader.Reader('../county_data/countyl010g.shp')
            counties = list(reader.geometries())
            COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())
            ax.add_feature(COUNTIES,
                           facecolor='none',
                           edgecolor='black',
                           linewidth=0.3)
        elif map_.map_type == 'tropical':
            countries = cfeature.NaturalEarthFeature(category='cultural',
                                                     name='admin_0_countries',
                                                     scale='50m',
                                                     facecolor='none')
            ax.add_feature(cfeature.LAND)
            ax.add_feature(countries, edgecolor='black', linewidth=0.5)

        # Set the additional info on the map
        ax.set_title('Daily High / Low / Percent Chance of Rain taken ' +
                     str(max_temperatures.validDate)[:-9] + ' UTC',
                     fontsize=12,
                     loc='left')
        text = AnchoredText(r'$\mathcircled{{c}}$ NickelBlock Forecasting',
                            loc=4,
                            prop={'size': 9},
                            frameon=True)
        ax.add_artist(text)

        # Data Model
        data_model = AnchoredText('NWS/NDFD CONUS model',
                                  loc=3,
                                  prop={'size': 9},
                                  frameon=True)
        ax.add_artist(data_model)

        # Add logo
        logo = Utils.get_logo()
        if map_.map_type == 'verywide':
            ax.figure.figimage(logo, 1140, 137, zorder=1)
        elif map_.map_type == 'regional':
            ax.figure.figimage(logo, 1000, 137, zorder=1)
        elif map_.map_type == 'local':
            ax.figure.figimage(logo, 973, 137, zorder=1)
        else:
            ax.figure.figimage(logo, 1140, 181, zorder=1)

        # Plot the cities' information
        if map_.map_type is not 'tropical':
            for city in map_.cities:
                for max_temp, min_temp, per_chance_rain in zip(
                        max_temperature_data, min_temperature_data,
                        percent_chance_rain_data):
                    if round(city.lat,
                             1) == round(max_temp['lat'], 1) and round(
                                 city.lon, 1) == round(max_temp['lon'], 1):
                        ax.plot(city.lon,
                                city.lat,
                                'ro',
                                zorder=9,
                                markersize=1.90,
                                transform=ccrs.Geodetic())

                        # City Name
                        if city.city_name == 'Pensacola' and map_.map_type == 'verywide':
                            ax.text(city.lon - 0.13,
                                    city.lat + 0.045,
                                    city.city_name,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())
                        elif map_.map_type == 'local':
                            ax.text(city.lon - 0.2,
                                    city.lat + 0.04,
                                    city.city_name,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())
                        else:
                            ax.text(city.lon - 0.45,
                                    city.lat + 0.07,
                                    city.city_name,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())

                        # City Min/Max Temperature
                        text = str(int(round(
                            min_temp['value'] * 1.8 - 459.67))) + ' / ' + str(
                                int(round(max_temp['value'] * 1.8 - 459.67)))
                        if map_.map_type == 'local':
                            ax.text(city.lon - 0.17,
                                    city.lat - 0.1,
                                    text,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())
                        else:
                            ax.text(city.lon - 0.34,
                                    city.lat - 0.175,
                                    text,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())

                        # City Percent Chance of Rain
                        text = str(int(round(per_chance_rain['value']))) + '%'
                        if map_.map_type == 'local':
                            ax.text(city.lon - 0.07,
                                    city.lat - 0.18,
                                    text,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())
                        else:
                            ax.text(city.lon - 0.2,
                                    city.lat - 0.36,
                                    text,
                                    fontsize='small',
                                    fontweight='bold',
                                    transform=ccrs.PlateCarree())
                        break

        plt.savefig('Day_{}_{}_DailyHighLowPerChanceRain.png'.format(
            day, map_.map_type))
        day += 1
Beispiel #21
0
def main():

    reader = shpreader.Reader('./county_data/countyl010g.shp')
    counties = list(reader.geometries())
    COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())

    ### List out all the cities you want plotted
    #  - MISSISSIPPI
    hattiesburg = City('Hattiesburg', 31.3271, -89.2903)
    jackson = City('Jackson', 32.2988, -90.1848)
    tupelo = City('Tupelo', 34.2576, -88.7034)
    # - LOUISIANA
    new_orleans = City('New Orleans', 29.9511, -90.0715)
    baton_rouge = City('Baton Rouge', 30.4515, -91.1871)
    shreveport = City('Shreveport', 32.5252, -93.7502)
    # - ALABAMA
    mobile = City('Mobile', 30.6954, -88.0399)
    montgomery = City('Montgomery', 32.3792, -86.3077)
    tuscaloosa = City('Tuscaloosa', 33.2098, -87.5692)
    huntsville = City('Huntsville', 34.7304, -86.5861)
    dothan = City('Dothan', 31.2232, -85.3905)
    # - TENNESSEE
    memphis = City('Memphis', 35.1495, -90.0490)
    jackson_tenn = City('Jackson', 35.6145, -88.8139)
    clarksville = City('Clarksville', 36.5298, -87.3595)
    knoxville = City('Knoxville', 35.9606, -83.9207)
    # - GEORGIA
    atlanta = City('Atlanta', 33.7490, -84.3880)
    macon = City('Macon', 32.8407, -83.6324)
    # - FLORIDA
    pensacola = City('Pensacola', 30.4213, -87.2169)
    tallahassee = City('Tallahassee', 30.4383, -84.2807)
    jacksonville = City('Jacksonville', 30.3322, -81.6557)
    # - ARKANSAS
    little_rock = City('Little Rock', 34.7465, -92.2896)
    fort_smith = City('Fort Smith', 35.3859, -94.3985)
    # - SOUTH CAROLINA
    augusta = City('Augusta', 33.4735, -82.0105)
    # - TEXAS
    houston = City('Houston', 29.7604, -95.3698)
    ###

    cities = [
        hattiesburg,
        jackson,
        tupelo,
        new_orleans,
        baton_rouge,
        mobile,
        montgomery,
        tuscaloosa,
        huntsville,
        dothan,
        memphis,
        pensacola,
        little_rock,
    ]

    # Create the figure and set the frame
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    ax.set_extent([-93.5, -84.5, 28.5, 35.5], crs=ccrs.Geodetic())

    # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth
    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')

    # Features for the figure
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.COASTLINE, edgecolor='lightgray')
    ax.add_feature(COUNTIES, facecolor='none', edgecolor='lightgray')
    ax.add_feature(states_provinces, edgecolor='gray')

    # Plot all the cities
    for city in cities:
        ax.plot(city.lon,
                city.lat,
                'ro',
                zorder=9,
                markersize=1.5,
                transform=ccrs.Geodetic())
        ax.text(city.lon,
                city.lat,
                city.city_name,
                fontsize='x-small',
                transform=ccrs.PlateCarree())

    # Company copyright on the bottom right corner
    SOURCE = 'NickelBlock Forecasting'
    text = AnchoredText(r'$\mathcircled{{c}}$ {}'
                        ''.format(SOURCE),
                        loc=4,
                        prop={'size': 9},
                        frameon=True)
    ax.add_artist(text)

    plt.show()
                         ax=ax[i],
                         title=True,
                         legend=True)
plt.savefig("o3_cbc_dif_megan.pdf", dpi=300, bbox_inches="tight")

# Spatial difference
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
import matplotlib.colors
from mpl_toolkits.axes_grid1 import make_axes_locatable

#loading MASP shapefile
reader_masp = shpreader.Reader("masp_shp/masp_shp.shp")
masp = list(reader_masp.geometries())
MASP = cfeature.ShapelyFeature(masp, ccrs.PlateCarree())

u10 = wrf.getvar(wrfout, "U10", timeidx=wrf.ALL_TIMES, method="cat")
v10 = wrf.getvar(wrfout, "V10", timeidx=wrf.ALL_TIMES, method="cat")

cbc_diff = ((o3_u_wrf - o3_u_wrf_cbc).sel(
    Time=slice("2014-10-05 21:00", "2014-10-13 00:00")).mean(dim="Time"))
u10_m = u10.sel(Time=slice("2014-10-05 21:00", "2014-10-13 00:00")).mean(
    dim="Time")
v10_m = v10.sel(Time=slice("2014-10-05 21:00", "2014-10-13 00:00")).mean(
    dim="Time")

val_limits = np.max([np.abs(cbc_diff.min()), cbc_diff.max()])

fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
cbc_diff.plot(x="XLONG",
Beispiel #23
0
 def useshapefile(self, directory, encoding='utf8', color=None, lw=None, **kwargs):
     if lw is None:
         lw = self.linewidth['province']
     kwargs.update(linewidth=lw)
     self.ax.add_feature(cfeature.ShapelyFeature(ciosr.Reader(directory).geometries(),
         ccrs.PlateCarree(), facecolor='none', edgecolor=color), **kwargs)
Beispiel #24
0
                            transform=ccrs.PlateCarree())
cwndspeedlbl = ax.clabel(contr_wndspeed,
                         fontsize=5,
                         colors='black',
                         inline=1,
                         inline_spacing=1,
                         fmt='%i')

for l in cwndspeedlbl:
    l.set_rotation(0)

# Use the cartopy shapefile reader to import FORECAST AREA.
reader = shpreader.Reader('/home/victoraalvarez/Documents/pythonScripts/'
                          'pythonPlayground/mapFiles/fa/fa3.shp')
fa = list(reader.geometries())
FA = cfeature.ShapelyFeature(fa, ccrs.PlateCarree())

ax.add_feature(FA,
               linewidth=1.5,
               facecolor='none',
               edgecolor='black',
               zorder=6,
               capstyle='round')
ax.add_feature(FA, linewidth=.5, facecolor='none', edgecolor='white', zorder=7)

# Add title & colorbar.
df = '%m/%d/%Y %H:%M'

plt.title("850MB WINDS", loc='left', fontsize=8, fontweight='bold', y=-0.09)
timestamp = datetime.utcnow().strftime(df) + "Z"
plt.title(timestamp, loc='right', fontsize=8, fontweight='bold', y=-0.09)
Beispiel #25
0
    def plot_ppi_map(fig, ax, cx, lon, lat, radar_data, title=None, normvar=None, cmap=None, \
                 cmap_bins=16, extend=None, projection=ccrs.PlateCarree(), orient="vertical", \
                clabel=None, continuously=False):
        """
        显示带底图的雷达图像
        :param fig:matplotlib的fig对象
        :param ax: axes对象
        :param cx:colorbar axes对象
        :param lon: 经度网格
        :param lat: 纬度网格
        :param radar_data: 雷达数据产品
        :param title: 画图的title
        :param normvar: cmap的最小最大值
        :param cmap:cmap的类型
        :param cmap_bins: cmap分多少段
        :param extend: 图像的lat lon的范围(minlon, maxlon, minlat, maxlat)
        :param projection: 地图的投影方式
        :param orient: colorbar的朝向
        :param clabel: colorbar的title
        :param continuously:使用采用连续的colorbar
        :return:
        """
        if normvar is None:
            vmin = -5
            vmax = 75
        else:
            vmin, vmax = normvar
        if extend is None:
            min_lon = np.min(lon)
            max_lon = np.max(lon)
            min_lat = np.min(lat)
            max_lat = np.max(lat)
        else:
            min_lon, max_lon, min_lat, max_lat = extend
        if title is None:
            title = ""
        if clabel is None:
            clabel = ""
        if continuously:
            cmap_bins = 256

        cmaps = plt.get_cmap(cmap)
        levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
        norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
        pm = ax.pcolormesh(lon,
                           lat,
                           radar_data,
                           transform=projection,
                           cmap=cmap,
                           norm=norm,
                           zorder=4)

        ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0)
        ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m',\
                                                    edgecolor='none', facecolor="white"), zorder=1)
        ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2)
        ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3)
        ax.set_extent([min_lon, max_lon, min_lat, max_lat], projection)
        ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), projection,\
                                               edgecolor='k', facecolor='none'), linewidth=0.5, \
                                                linestyle='-' , zorder=5, alpha=0.8)
        if continuously:
            cbar = fig.colorbar(mappable=pm, cax=cx, ax=ax, orientation=orient)
        else:
            cbar = fig.colorbar(mappable=pm,
                                cax=cx,
                                ax=ax,
                                orientation=orient,
                                ticks=levels)
            cbar.set_ticklabels(RadarGraphMap._FixTicks(levels))
        cbar.set_label(clabel)
        #ax.set_aspect("equal")
        ax.set_title(title, fontsize=15)
        parallels = np.arange(int(min_lat), math.ceil(max_lat) + 1, 1)
        meridians = np.arange(int(min_lon), math.ceil(max_lon) + 1, 1)
        ax.set_xticks(meridians, crs=projection)
        ax.set_yticks(parallels, crs=projection)
        lon_formatter = LongitudeFormatter()
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
Beispiel #26
0
    extent[2], extent[3], extent[0], extent[1], from_date, to_date)

if not os.path.exists(working_dir):
    os.makedirs(working_dir)

f = open('full.data', 'rb')
storedlist = pickle.load(f)

# Map GHI
storedlist = storedlist[0]

reader = Reader(os.path.join('shape', 'Province_9.shp'))

proj = ccrs.PlateCarree()
provinces = cfeat.ShapelyFeature(reader.geometries(),
                                 proj,
                                 edgecolor='k',
                                 facecolor='none')

for i in range(total_frame):
    print("%f%%\r" % (i / total_frame * 100))
    time = int(i / total_frame * time_range)

    plt.figure(figsize=(10, 10))
    ax = plt.axes(projection=proj)

    ax.add_feature(provinces, linewidth=0.5)
    ax.set_extent(extent, crs=proj)
    ax.stock_img()
    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=1.2,
Beispiel #27
0
"""
Created on Tue Jul 28 10:51:47 2020

@author: aristizabal
"""

lon_lim = [-110.0, -10.0]
lat_lim = [15.0, 45.0]

import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader

file_EEZs = '/Users/aristizabal/Desktop/MARACOOS_project/Maria_scripts/World_EEZ_v11_20191118/eez_boundaries_v11.shp'

fig, ax = plt.subplots(figsize=(10, 5),
                       subplot_kw=dict(projection=cartopy.crs.PlateCarree()))
coast = cfeature.NaturalEarthFeature('physical', 'coastline', '10m')
ax.add_feature(coast, edgecolor='black', facecolor='none')
ax.add_feature(cfeature.BORDERS)  # adds country borders
ax.add_feature(cfeature.STATES)

shape_feature = cfeature.ShapelyFeature(Reader(file_EEZs).geometries(),
                                        ccrs.PlateCarree(),
                                        edgecolor='grey',
                                        facecolor='none')
ax.add_feature(shape_feature, zorder=1)
plt.axis([-100, -10, 0, 50])
Beispiel #28
0
def main():
    download_dataset()

    parser = argparse.ArgumentParser()
    parser.add_argument('-m',
                        '--map',
                        help='Which type of map to be generated.')
    args = parser.parse_args()

    if args.map == 'verywide':
        map_ = map_utils.VeryWide()
    elif args.map == 'regional':
        map_ = map_utils.Regional()
    elif args.map == 'local':
        map_ = map_utils.Local()
    elif args.map == 'tropical':
        map_ = map_utils.Tropical()
    elif args.map == 'country':
        map_ = map_utils.Country()

    # Open dataset and capture relevant info
    file = '../output/CPC_data.grb2'
    dataset = pygrib.open(file)

    # Grab the temperature and precipitation data from the dataset
    precipitation_data = []
    temperature_data = dataset.select(name='Temperature')
    for d in dataset:
        if str(d) not in str(temperature_data):
            precipitation_data.append(d)

    temperature_precipitation_data = {
        'Temperatures': temperature_data,
        'Precipitations': precipitation_data,
    }.items()

    for key, values in temperature_precipitation_data:
        fig = plt.figure(figsize=(15, 9))
        ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator())
        ax.set_extent(map_.NorthSouthEastWest[::-1], crs=ccrs.Geodetic())
        for value in values:
            lats, lons = value.latlons()
            vals = value.values
            # Add boundaries to plot
            ax.add_feature(cfeature.OCEAN, facecolor=cfeature.COLORS['water'])
            if map_.map_type == 'verywide':
                ax.add_feature(cfeature.STATES.with_scale('50m'),
                               linewidth=0.5)
            elif map_.map_type == 'regional' or map_.map_type == 'local':
                ax.add_feature(cfeature.STATES.with_scale('50m'),
                               linewidth=0.5)
                reader = shpreader.Reader('../county_data/countyl010g.shp')
                counties = list(reader.geometries())
                COUNTIES = cfeature.ShapelyFeature(counties,
                                                   ccrs.PlateCarree())
                ax.add_feature(COUNTIES,
                               facecolor='none',
                               edgecolor='black',
                               linewidth=0.3)
            elif map_.map_type == 'tropical' or map_.map_type == 'country':
                countries = cfeature.NaturalEarthFeature(
                    category='cultural',
                    name='admin_0_countries',
                    scale='50m',
                    facecolor='none')
                ax.add_feature(cfeature.LAND)
                ax.add_feature(countries, edgecolor='black', linewidth=0.5)
                ax.add_feature(cfeature.STATES.with_scale('50m'),
                               linewidth=0.5)

            # Contour temperature value at each lat/lon depending on the key
            if 'event below' in str(value):
                if key == 'Temperatures':
                    # Contour temperature at each lat/long
                    cf = ax.contourf(lons,
                                     lats,
                                     vals,
                                     levels=[33, 40, 50, 60, 70, 80, 90],
                                     transform=ccrs.PlateCarree(),
                                     cmap='Blues')
                    cb1 = plt.colorbar(cf,
                                       ax=ax,
                                       orientation='horizontal',
                                       fraction=0.045,
                                       pad=0.04)
                elif key == 'Precipitations':
                    # Contour temperature at each lat/long
                    cf = ax.contourf(lons,
                                     lats,
                                     vals,
                                     levels=[33, 40, 50, 60, 70, 80, 90],
                                     transform=ccrs.PlateCarree(),
                                     cmap='Blues')
                    cb1 = plt.colorbar(cf,
                                       ax=ax,
                                       orientation='horizontal',
                                       fraction=0.035,
                                       pad=0.08)
                cb1.ax.set_xlabel('Probability of Below (%)')
            elif 'event above' in str(value):
                if key == 'Temperatures':
                    # Contour temperature at each lat/long
                    cf = ax.contourf(lons,
                                     lats,
                                     vals,
                                     levels=[33, 40, 50, 60, 70, 80, 90],
                                     transform=ccrs.PlateCarree(),
                                     cmap='Reds')
                    cb2 = plt.colorbar(cf,
                                       ax=ax,
                                       orientation='horizontal',
                                       fraction=0.0395,
                                       pad=0.08)
                elif key == 'Precipitations':
                    # Contour temperature at each lat/long
                    cf = ax.contourf(lons,
                                     lats,
                                     vals,
                                     levels=[33, 40, 50, 60, 70, 80, 90],
                                     transform=ccrs.PlateCarree(),
                                     cmap='Greens')
                    cb2 = plt.colorbar(cf,
                                       ax=ax,
                                       orientation='horizontal',
                                       fraction=0.0395,
                                       pad=0.04)
                cb2.ax.set_xlabel('Probability of Above (%)')

            # Plot all the cities
            if map_.map_type is not 'tropical' and map_.map_type is not 'country':
                for city in map_.cities:
                    ax.plot(city.lon,
                            city.lat,
                            'ro',
                            zorder=9,
                            markersize=1.90,
                            transform=ccrs.Geodetic())

                    if map_.map_type == 'local':
                        ax.text(city.lon - 0.3,
                                city.lat + 0.04,
                                city.city_name,
                                fontsize='small',
                                fontweight='bold',
                                transform=ccrs.PlateCarree())
                    else:
                        ax.text(city.lon - 0.5,
                                city.lat + 0.09,
                                city.city_name,
                                fontsize='small',
                                fontweight='bold',
                                transform=ccrs.PlateCarree())
            # Title
            ax.set_title('{} Probability for {} UTC'.format(
                key, str(value.validDate)),
                         fontsize=12,
                         loc='left')

            # Company copyright bottom right corner
            text = AnchoredText(r'$\mathcircled{{c}}$ NickelBlock Forecasting',
                                loc=4,
                                prop={'size': 9},
                                frameon=True)
            ax.add_artist(text)

            # Data model
            data_model = AnchoredText('CPC Probability Outlook model',
                                      loc=3,
                                      prop={'size': 9},
                                      frameon=True)
            ax.add_artist(data_model)

            # Add logo
            logo = Utils.get_logo()
            if map_.map_type == 'verywide':
                if key == 'Temperatures':
                    ax.figure.figimage(logo, 1040, 272, zorder=1)
                elif key == 'Precipitations':
                    ax.figure.figimage(logo, 1045, 265, zorder=1)
            elif map_.map_type == 'regional':
                if key == 'Temperatures':
                    ax.figure.figimage(logo, 925, 273, zorder=1)
                elif key == 'Precipitations':
                    ax.figure.figimage(logo, 930, 267, zorder=1)
            elif map_.map_type == 'local':
                if key == 'Temperatures':
                    ax.figure.figimage(logo, 904, 270, zorder=1)
                elif key == 'Precipitations':
                    ax.figure.figimage(logo, 909, 265, zorder=1)
            elif map_.map_type == 'tropical':
                if key == 'Temperatures':
                    ax.figure.figimage(logo, 1110, 272, zorder=1)
                elif key == 'Precipitations':
                    ax.figure.figimage(logo, 1115, 267, zorder=1)
            elif map_.map_type == 'country':
                if key == 'Temperatures':
                    ax.figure.figimage(logo, 1070, 271, zorder=1)
                elif key == 'Precipitations':
                    ax.figure.figimage(logo, 1075, 266, zorder=1)

        plt.savefig('CPC_{}_{}_Map.png'.format(key, value.validDate))
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import cartopy.feature as cfeature

import boto3
from botocore.handlers import disable_signing

# In[ ]:

# In[63]:

reader = shpreader.Reader(
    r'C:\Users\iac6311\Documents\Work\Data\GIS\USA\tl_2016_17_cousub\tl_2016_17_cousub.shp'
)
counties = list(reader.geometries())
COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())

# Read the gauge locations file and gauge observations file into pandas dataframes, and get the location coordinates.

# In[64]:

# load CCN gauge locations
CCN_gauge_locations_fname = 'C:/Users/iac6311/Documents/Work/Data/Cook_County/CookCounty_gage_locations.csv'
# load CCN gauge observations
CCN_gauge_observations_fname = 'C:/Users/iac6311/Documents/Work/Data/Cook_County/WaterYear2013.csv'

df_gauge_loc = pd.read_csv(CCN_gauge_locations_fname, header=0)
df_gauge = pd.read_csv(CCN_gauge_observations_fname, header=0)

x = df_gauge_loc['Longitude - West'].values
y = df_gauge_loc['Latitude'].values
Beispiel #30
0
def draw_map(adict, override_scenario=False):
    """If adict['imtype'] is MMI, draw a map of intensity draped over
    topography, otherwise Draw IMT contour lines over hill-shaded topography.

    Args:
        adict (dictionary): A dictionary containing the following keys:
            'imtype' (str): The intensity measure type
            'topogrid' (Grid2d): A topography grid
            'allcities' (Cities): A list of global cities,
            'states_provinces' (Cartopy Feature): States/province boundaries.
            'countries' (Cartopy Feature): Country boundaries.
            'oceans' (Cartopy Feature): Oceans.
            'lakes' (Cartopy Feature): Lakes.
            'roads' (Shapely Feature): Roads.
            'faults' (Shapely Feature): Fault traces
            'datadir' (str): The path into which to deposit products
            'operator' (str): The producer of this shakemap
            'filter_size' (int): The size of the filter used before contouring
            'info' (dictionary): The shakemap info structure
            'component' (str): The intensity measure component being plotted
            'imtdict' (dictionary): Dict containing the IMT grids
            'rupdict' (dictionary): Dict containing the rupture data
            'stationdict' (dictionary): Dict of station data
            'config' (dictionary): The configuration data for this shakemap
            'tdict' (dictionary): The text strings to be printed on the map
                in the user's choice of language.
        override_scenario (bool): Turn off scenario watermark.

    Returns:
        Tuple of (Matplotlib figure, Matplotlib figure): Objects containing
        the map generated by this function, and the intensity legend,
        respectively. If the imtype of this map is not 'MMI', the second
        element of the tuple will be None.
    """
    imtype = adict['imtype']
    imtdict = adict['imtdict']  # mmidict
    imtdata = imtdict['mean']  # mmidata
    gd = GeoDict(imtdict['mean_metadata'])
    imtgrid = Grid2D(imtdata, gd)  # mmigrid

    gd = imtgrid.getGeoDict()

    # Retrieve the epicenter - this will get used on the map
    rupture = rupture_from_dict(adict['ruptdict'])
    origin = rupture.getOrigin()
    center_lat = origin.lat
    center_lon = origin.lon

    # load the cities data, limit to cities within shakemap bounds
    cities = adict['allcities'].limitByBounds(
        (gd.xmin, gd.xmax, gd.ymin, gd.ymax))

    # get the map boundaries and figure size
    bounds, figsize, aspect = _get_map_info(gd)

    # Note: dimensions are: [left, bottom, width, height]
    dim_left = 0.1
    dim_bottom = 0.19
    dim_width = 0.8
    dim_height = dim_width / aspect

    # Create the MercatorMap object, which holds a separate but identical
    # axes object used to determine collisions between city labels.
    mmap = MercatorMap(
        bounds,
        figsize,
        cities,
        padding=0.5,
        dimensions=[dim_left, dim_bottom, dim_width, dim_height])
    fig = mmap.figure
    ax = mmap.axes
    # this needs to be done here so that city label collision
    # detection will work
    fig.canvas.draw()

    # get the geographic projection object
    geoproj = mmap.geoproj
    # get the mercator projection object
    proj = mmap.proj
    # get the proj4 string - used by Grid2D project() method
    projstr = proj.proj4_init

    # get the projected IMT and topo grids
    pimtgrid, ptopogrid = _get_projected_grids(imtgrid, adict['topogrid'],
                                               projstr)

    # get the projected geodict
    proj_gd = pimtgrid.getGeoDict()

    pimtdata = pimtgrid.getData()
    ptopo_data = ptopogrid.getData()

    mmimap = ColorPalette.fromPreset('mmi')

    if imtype == 'MMI':
        draped_hsv = _get_draped(pimtdata, ptopo_data, mmimap)
    else:
        # get the draped topo data
        topo_colormap = ColorPalette.fromPreset('shaketopo')
        draped_hsv = _get_shaded(ptopo_data, topo_colormap)
        # convert units
        if imtype == 'PGV':
            pimtdata = np.exp(pimtdata)
        else:
            pimtdata = np.exp(pimtdata) * 100

    plt.sca(ax)
    ax.set_xlim(proj_gd.xmin, proj_gd.xmax)
    ax.set_ylim(proj_gd.ymin, proj_gd.ymax)
    img_extent = (proj_gd.xmin, proj_gd.xmax, proj_gd.ymin, proj_gd.ymax)

    plt.imshow(draped_hsv,
               origin='upper',
               extent=img_extent,
               zorder=IMG_ZORDER,
               interpolation='none')

    config = adict['config']
    gmice = get_object_from_config('gmice', 'modeling', config)
    gmice_imts = gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES
    gmice_pers = gmice.DEFINED_FOR_SA_PERIODS

    oqimt = imt.from_string(imtype)

    if imtype != 'MMI' and (not isinstance(oqimt, tuple(gmice_imts)) or
                            (isinstance(oqimt, imt.SA)
                             and oqimt.period not in gmice_pers)):
        my_gmice = None
    else:
        my_gmice = gmice

    if imtype != 'MMI':
        # call the contour module in plotting to get the vertices of the
        # contour lines
        contour_objects = contour(imtdict, imtype, adict['filter_size'],
                                  my_gmice)

        # get a color palette for the levels we have
        # levels = [c['properties']['value'] for c in contour_objects]

        # cartopy shapely feature has some weird behaviors, so I had to go
        # rogue and draw contour lines/labels myself.
        # draw dashed contours first, the ones over land will be overridden by
        # solid contours
        npoints = []
        for contour_object in contour_objects:
            props = contour_object['properties']
            multi_lines = sShape(contour_object['geometry'])
            pmulti_lines = proj.project_geometry(multi_lines, src_crs=geoproj)
            for multi_line in pmulti_lines:
                pmulti_line = mapping(multi_line)['coordinates']
                x, y = zip(*pmulti_line)
                npoints.append(len(x))
                # color = imt_cmap.getDataColor(props['value'])
                ax.plot(x,
                        y,
                        color=props['color'],
                        linestyle='dashed',
                        zorder=DASHED_CONTOUR_ZORDER)

        white_box = dict(boxstyle="round",
                         ec=(0, 0, 0),
                         fc=(1., 1, 1),
                         color='k')

        # only label lines with lots of points
        npoints = np.array(npoints)
        # min_npoints = npoints.mean() - (npoints.std()/2)
        min_npoints = npoints.mean()

        # draw solid contours next - the ones over water will be covered by
        # ocean polygon
        for contour_object in contour_objects:
            props = contour_object['properties']
            multi_lines = sShape(contour_object['geometry'])
            pmulti_lines = proj.project_geometry(multi_lines, src_crs=geoproj)
            for multi_line in pmulti_lines:
                pmulti_line = mapping(multi_line)['coordinates']
                x, y = zip(*pmulti_line)
                # color = imt_cmap.getDataColor(props['value'])
                ax.plot(x,
                        y,
                        color=props['color'],
                        linestyle='solid',
                        zorder=CONTOUR_ZORDER)
                if len(x) > min_npoints:
                    # try to label each segment with black text in a white box
                    xc = x[int(len(x) / 3)]
                    yc = y[int(len(y) / 3)]
                    if _label_close_to_edge(xc, yc, proj_gd.xmin, proj_gd.xmax,
                                            proj_gd.ymin, proj_gd.ymax):
                        continue
                    # TODO: figure out if box is going to go outside the map,
                    # if so choose a different point on the line.
                    ax.text(xc,
                            yc,
                            '%.1f' % props['value'],
                            size=8,
                            ha="center",
                            va="center",
                            bbox=white_box,
                            zorder=AXES_ZORDER - 1)

    # make the border thicker
    lw = 2.0
    ax.outline_patch.set_zorder(BORDER_ZORDER)
    ax.outline_patch.set_linewidth(lw)
    ax.outline_patch.set_joinstyle('round')
    ax.outline_patch.set_capstyle('round')

    # Coastlines will get drawn when we draw the ocean edges
    # ax.coastlines(resolution="10m", zorder=COAST_ZORDER, linewidth=3)

    if adict['states_provinces']:
        ax.add_feature(adict['states_provinces'],
                       edgecolor='0.5',
                       zorder=COAST_ZORDER)

    if adict['countries']:
        ax.add_feature(adict['countries'],
                       edgecolor='black',
                       zorder=BORDER_ZORDER)

    if adict['oceans']:
        ax.add_feature(adict['oceans'], edgecolor='black', zorder=OCEAN_ZORDER)

    if adict['lakes']:
        ax.add_feature(adict['lakes'], edgecolor='black', zorder=OCEAN_ZORDER)

    if adict['faults'] is not None:
        ax.add_feature(adict['faults'],
                       edgecolor='firebrick',
                       zorder=ROAD_ZORDER)

    if adict['roads'] is not None:
        ax.add_feature(adict['roads'], edgecolor='dimgray', zorder=ROAD_ZORDER)

    # draw graticules, ticks, tick labels
    _draw_graticules(ax, *bounds)

    # is this event a scenario?
    info = adict['info']
    etype = info['input']['event_information']['event_type']
    is_scenario = etype == 'SCENARIO'

    if is_scenario and not override_scenario:
        plt.text(center_lon,
                 center_lat,
                 adict['tdict']['title_parts']['scenario'],
                 fontsize=72,
                 zorder=SCENARIO_ZORDER,
                 transform=geoproj,
                 alpha=WATERMARK_ALPHA,
                 color=WATERMARK_COLOR,
                 horizontalalignment='center',
                 verticalalignment='center',
                 rotation=45,
                 path_effects=[
                     path_effects.Stroke(linewidth=1, foreground='black')
                 ])

    # Draw the map scale in the unoccupied lower corner.
    corner = 'll'
    draw_scale(ax, corner, pady=0.05, padx=0.05, zorder=SCALE_ZORDER)

    # draw cities
    mmap.drawCities(shadow=True, zorder=CITIES_ZORDER, draw_dots=True)

    # Draw the epicenter as a black star
    plt.sca(ax)
    plt.plot(center_lon,
             center_lat,
             'k*',
             markersize=16,
             zorder=EPICENTER_ZORDER,
             transform=geoproj)

    # draw the rupture polygon(s) in black, if not point rupture
    point_source = True
    if not isinstance(rupture, PointRupture):
        point_source = False
        json_dict = rupture._geojson
        # shapes = []
        for feature in json_dict['features']:
            rup_shape = sShape(feature['geometry'])
            sfeature = cfeature.ShapelyFeature(rup_shape, geoproj)
            ax.add_feature(sfeature,
                           zorder=FAULT_ZORDER,
                           lw=1,
                           edgecolor='k',
                           facecolor=(0, 0, 0, 0))

    # draw the station data on the map
    stations = adict['stationdict']
    _draw_stations(ax, stations, imtype, mmimap, geoproj)

    _draw_title(imtype, adict)

    process_time = info['processing']['shakemap_versions']['process_time']
    map_version = int(info['processing']['shakemap_versions']['map_version'])
    if imtype == 'MMI':
        _draw_mmi_legend(fig, mmimap, gmice, process_time, map_version,
                         point_source, adict['tdict'])
        # make a separate MMI legend
        fig2 = plt.figure(figsize=figsize)
        _draw_mmi_legend(fig2, mmimap, gmice, process_time, map_version,
                         point_source, adict['tdict'])

    else:
        _draw_imt_legend(fig, mmimap, imtype, gmice, process_time, map_version,
                         point_source, adict['tdict'])
        plt.draw()
        fig2 = None

    return (fig, fig2)