コード例 #1
0
def plot_contour(lat,
                 lon,
                 grid,
                 ax=None,
                 extent=None,
                 tiler=StamenTerrain(),
                 zoom=6,
                 N=7,
                 fontsize=10,
                 fmt='%1.1f',
                 add_gridlines=True,
                 **kwargs):
    if ax is None:
        plt.figure(figsize=(10, 8))
        ax = plt.axes(projection=ccrs.PlateCarree())
    if extent is not None:
        xmin, xmax, ymin, ymax = extent
        x = lon[xmin:xmax]
        y = lat[ymin:ymax]
        z = grid[ymin:ymax, xmin:xmax]
    elif lon.shape[0] != grid.shape[1]:
        x = (lon[:-1] + lon[1:]) / 2.
        y = (lat[:-1] + lat[1:]) / 2.
        z = grid
    else:
        x = lon
        y = lat
        z = grid
    CS = plt.contour(x, y, z, N, cmap='Greys', **kwargs)
    plt.clabel(CS, inline=1, fontsize=fontsize, fmt=fmt)
    if tiler:
        ax.add_image(tiler, zoom)
    if add_gridlines:
        ax = gridlines(ax)
    return ax
コード例 #2
0
ファイル: visualize.py プロジェクト: yannikbehr/spectroscopy
def plot_gasflow(gf, vent=None, scale=100., **kargs):
    if vent is None:
        raise VizException("Please provide a vent location (lon, lat)")

    pos = gf.position[:]
    vx = gf.vx[:]
    vy = gf.vy[:]
    lon_min = vent[0] - 0.03
    lon_max = vent[0] + 0.03
    lat_min = vent[1] - 0.03
    lat_max = vent[1] + 0.03
    tiler = StamenTerrain()
    mercator = tiler.crs
    fig = plt.figure(figsize=(10, 10))
    ax = plt.axes(projection=mercator)
    fig.add_axes(ax)
    ax.add_image(tiler, 11)
    p = ccrs.PlateCarree()
    g = pyproj.Geod(ellps='WGS84')
    for lon, lat, _vx, _vy in zip(pos[:, 0], pos[:, 1], vx, vy):
        wd = vec2bearing(_vx, _vy)
        ws = np.sqrt(_vx * _vx + _vy * _vy)*scale
        elon, elat, _ = g.fwd(lon, lat, wd, ws)
        x, y = p.transform_points(ccrs.Geodetic(),
                                  np.array([lon, elon]),
                                  np.array([lat, elat]))
        dx = y[0] - x[0]
        dy = y[1] - x[1]
        ax.quiver(np.array([x[0]]), np.array([x[1]]), np.array([dx]),
                  np.array([dy]), transform=ccrs.PlateCarree())
    ax.scatter(vent[0], vent[1], marker='^', color='red', s=50,
               transform=ccrs.Geodetic())
    ax.set_extent([lon_min, lon_max, lat_min, lat_max])
    return fig
コード例 #3
0
ファイル: plotting.py プロジェクト: tmilliman/pyphenocam
    def __init__(self, networksites=[], *args, **kwargs):

        if 'fig' not in kwargs:
            kwargs['fig'] = plt.gcf()

        self.tiler = StamenTerrain()
        kwargs['map_projection'] = self.tiler.crs
        if 'rect' not in kwargs:
            kwargs['rect'] = [0, 0, 1, 1]
        super(LocatorMap, self).__init__(*args, **kwargs)
        self.add_image(self.tiler, 3)

        self.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())
        self.set_title('US Phenocam Network')
        self.coastlines()

        states_provinces = cfeature.NaturalEarthFeature(
            category='cultural',
            name='admin_1_states_provinces_lines',
            scale='50m',
            facecolor='none')

        self.add_feature(states_provinces, edgecolor='gray')
        self.add_feature(cartopy.feature.BORDERS, lw=2)

        self.networksites = networksites

        self.load_sites()

        self.cursite = None
        self.cur_annotation = None
        self.hov_annotation = None
コード例 #4
0
def main():
    tiler = StamenTerrain()
    mercator = tiler.crs
    ax = plt.axes(projection=mercator)
    ax.set_extent([-90, -73, 22, 34])

    ax.add_image(tiler, 6)

    ax.coastlines('10m')
    plt.show()
コード例 #5
0
def test_radarmapdisplay_cartopy_preexisting_ax(outfile=None):
    import cartopy
    from cartopy.io.img_tiles import StamenTerrain
    radar = pyart.io.read_cfradial(pyart.testing.CFRADIAL_PPI_FILE)
    display = pyart.graph.RadarMapDisplay(radar, shift=(0.1, 0.0))
    fig = plt.figure()
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_image(StamenTerrain(), 6)
    display.plot_ppi_map('reflectivity_horizontal', 0, ax=ax, embelish=False)
    if outfile:
        fig.savefig(outfile)
    plt.close()
コード例 #6
0
ファイル: image_tiles.py プロジェクト: yangboyd/cartopy
def main():
    tiler = StamenTerrain()
    mercator = tiler.crs

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection=mercator)
    ax.set_extent([-90, -73, 22, 34], crs=ccrs.PlateCarree())

    ax.add_image(tiler, 6)

    ax.coastlines('10m')
    plt.show()
コード例 #7
0
    def draw_roi(self):
        '''
        Helper function for seeing the region of interest being queried
        '''

        fig, ax = plt.subplots(1, figsize=(8,8), subplot_kw={'projection': ccrs.PlateCarree()})
        ax.set_extent((self.min_lon-1, self.max_lon+1, self.min_lat-1, self.max_lat+1))
        ax.add_image(StamenTerrain(), 8)
        ax.coastlines(resolution='10m')
        ax.gridlines(draw_labels=True, color='0.8')

        query_bbox_shp = shpgeom.box(self.min_lon, self.min_lat, self.max_lon, self.max_lat)
        query_bbox_gs = gpd.GeoSeries(query_bbox_shp)

        query_bbox_gs.plot(ax=ax, facecolor='none', edgecolor='red', linewidth=3)
コード例 #8
0
def get_map_params(image='StamenTerrain', color_palette=None):
    # set color palette
    if color_palette:
        cmap = plt.get_cmap(color_palette)
    else:
        cmap = None

    # set background image
    if image == 'StamenTerrain':
        tiler = StamenTerrain()
    elif image == 'GoogleTiles':
        tiler = GoogleTiles()
    elif image == 'OSM':
        tiler = OSM()

    return cmap, tiler
コード例 #9
0
def plot_contingency(x, y, contingency, title):
    """
    Prepare a geographical map of a contingency score map, with appropriate coloring
    """
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import cartopy
    from matplotlib import colors
    from cartopy.io.img_tiles import StamenTerrain
    import matplotlib.pyplot as plt
    plot_image = np.ma.masked_where(contingency==0, contingency)
    extent = (x.min()-(x[1]-x[0])*0.5, x.max()+(x[1]-x[0])*0.5, y.min()-np.abs(y[1]-y[0])*0.5, y.max()+np.abs(y[1]-y[0])*0.5)
    cmap = colors.ListedColormap(['blue', 'red', 'green'])
    bounds=[0.5, 1.5, 2.5, 3.5]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    tiler = StamenTerrain()
    mercator = tiler.crs
    fig =plt.figure(figsize=(10,10))
    ax = fig.add_subplot(111, axisbg='None', projection=mercator) # mercator
    # get hold of the coastlines for that area.
#     ax.add_feature(cartopy.feature.LAND, zorder=1)
#     ax.add_feature(cartopy.feature.OCEAN, zorder=1)
#     ax.add_feature(cartopy.feature.COASTLINE)
#     ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
#     ax.add_feature(cartopy.feature.LAKES, alpha=0.5)
#     ax.add_feature(cartopy.feature.RIVERS)
#     ax.stock_img()
    ax.set_extent(extent)
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=1, color='gray', alpha=0.5, linestyle='--')
#     ax.background_patch.set_fill(False)
    ax.add_image(tiler, 9, zorder=1)
    img = ax.imshow(plot_image, extent=extent, vmin=1., vmax=3., interpolation='nearest', 
                        cmap=cmap, norm=norm, zorder=3, transform=ccrs.PlateCarree())  # origin='lower', transform=mercator
    ax.set_xlabel('longitude')
    ax.set_ylabel('latitude')


    # make a color bar
    cbar = plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[1, 2, 3], orientation='horizontal')

    cbar.ax.set_xticklabels(['Global only', 'Local only', 'Both'])
    fig.suptitle(title, fontsize=14)
    fig.savefig('{:s}.png'.format(title), bbox_inches='tight', dpi=300)
コード例 #10
0
def draw_figure(df, fileout):
	geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84'))
	fig=plt.figure(frameon=False)
	tiler = StamenTerrain()
	ax = plt.axes(projection=tiler.crs)
	ax.add_feature(cartopy.feature.OCEAN,zorder=1)
	ax.add_feature(cartopy.feature.COASTLINE,edgecolor='green',linewidth=0.5,zorder=4)
	ax.add_feature(cartopy.feature.BORDERS,edgecolor='green',linewidth=0.5,zorder=4)

	tra = tiler.crs.transform_points(geodetic,df.lon.values,df.lat.values)
	x = tra[:,0]
	y = tra[:,1]
	tra = pd.DataFrame({'lon':x,'lat':y,'baroaltitude':df.baroaltitude.values})
	target = 6000
	ratio = target/(np.max(tra.lon)-np.min(tra.lon))
	cvs = ds.Canvas(plot_width=target, plot_height=int((np.max(tra.lat)-np.min(tra.lat))*ratio))

	agg = cvs.points(tra, 'lon', 'lat',ds.min('baroaltitude'))#, ds.mean('baroaltitude'))
	img = tf.shade(agg, cmap=inferno,how='linear')
	img = tf.set_background(img, 'black')
	r = img.to_pil()

	datas = r.getdata()

	newData = []
	for item in datas:
		if item[0] == 0 and item[1] == 0 and item[2] == 0:
		    newData.append((255, 255, 255, 0))
		else:
		    newData.append(item)

	r.putdata(newData)
	cax = plt.imshow(r,zorder=3,origin='upper',interpolation='gaussian',extent=(np.min(tra.lon),np.max(tra.lon),np.min(tra.lat),np.max(tra.lat)))
	ax1 = fig.add_axes([0.05, 0.18, 0.9, 0.025])
	norm = mpl.colors.Normalize(vmin=np.min(df.baroaltitude.values)/FEET2METER, vmax=np.max(df.baroaltitude.values)/FEET2METER)
	cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=infernompl,norm=norm,orientation='horizontal')
	cb1.set_label('$H_p$ [ft]')

	size = fig.get_size_inches()
	h_over_w = size[1]/size[0]
	fig.set_tight_layout({'pad':0})
	fig.set_figwidth(TEXT_WIDTH)
	fig.set_figheight(TEXT_WIDTH*h_over_w)
	plt.savefig(fileout,format="pdf",pad_inches=0,dpi=2000, bbox_inches='tight')
コード例 #11
0
def feature_locations(df,
                      ax=None,
                      figsize=(14, 8),
                      tiler=StamenTerrain(),
                      lat='centroidY',
                      lon='centroidX',
                      paths=False,
                      features=True,
                      zoom=6,
                      zorder=5,
                      colorby='ComplexNum',
                      c='k'):
    '''
    Use a computed titanized dataframe to show all the features and their paths
    '''
    if ax is None:
        plt.figure(figsize=figsize)
        ax = plt.axes(projection=ccrs.PlateCarree())
        background(ax)
        ax.add_image(tiler, zoom)
    if features:
        storm_names = dict([(n[1], n[0])
                            for n in enumerate(df[colorby].unique())])
        df.plot.scatter(x=lon,
                        y=lat,
                        c=[storm_names[n] for n in df[colorby]],
                        ax=ax,
                        cmap='rainbow',
                        yticks=[],
                        edgecolor='None',
                        s=50,
                        zorder=zorder)
    if paths:
        gb = df.groupby(df['ComplexNum'])
        for k, v in gb.groups.items():
            gb.get_group(k).plot(x=lon,
                                 y=lat,
                                 c=c,
                                 ax=ax,
                                 legend=None,
                                 zorder=zorder + 1)
    return ax
コード例 #12
0
def main():
    # Define the two coordinate systems with different ellipses.
    wgs84 = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84'))
    sphere = ccrs.PlateCarree(
        globe=ccrs.Globe(datum='WGS84', ellipse='sphere'))

    # Define the coordinate system of the data we have from Natural Earth and
    # acquire the 1:10m physical coastline shapefile.
    geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84'))
    dataset = cfeature.NaturalEarthFeature(category='physical',
                                           name='coastline',
                                           scale='10m')

    # Create a Stamen map tiler instance, and use its CRS for the GeoAxes.
    tiler = StamenTerrain()
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection=tiler.crs)
    ax.set_title('The effect of incorrectly referencing the Solomon Islands')

    # Pick the area of interest. In our case, roughly the Solomon Islands, and
    # get hold of the coastlines for that area.
    extent = [155, 163, -11.5, -6]
    ax.set_extent(extent, geodetic)
    geoms = list(dataset.intersecting_geometries(extent))

    # Add the Stamen aerial imagery at zoom level 7.
    ax.add_image(tiler, 7)

    # Transform the geodetic coordinates of the coastlines into the two
    # projections of differing ellipses.
    wgs84_geoms = [
        geom_transform(transform_fn_factory(wgs84, geodetic), geom)
        for geom in geoms
    ]
    sphere_geoms = [
        geom_transform(transform_fn_factory(sphere, geodetic), geom)
        for geom in geoms
    ]

    # Using these differently referenced geometries, assume that they are
    # both referenced to WGS84.
    ax.add_geometries(wgs84_geoms, wgs84, edgecolor='white', color='none')
    ax.add_geometries(sphere_geoms, wgs84, edgecolor='gray', color='none')

    # Create a legend for the coastlines.
    legend_artists = [
        Line([0], [0], color=color, linewidth=3) for color in ('white', 'gray')
    ]
    legend_texts = ['Correct ellipse\n(WGS84)', 'Incorrect ellipse\n(sphere)']
    legend = ax.legend(legend_artists,
                       legend_texts,
                       fancybox=True,
                       loc='lower left',
                       framealpha=0.75)
    legend.legendPatch.set_facecolor('wheat')

    # Create an inset GeoAxes showing the location of the Solomon Islands.
    sub_ax = fig.add_axes([0.7, 0.625, 0.2, 0.2],
                          projection=ccrs.PlateCarree())
    sub_ax.set_extent([110, 180, -50, 10], geodetic)

    # Make a nice border around the inset axes.
    effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5)
    sub_ax.outline_patch.set_path_effects([effect])

    # Add the land, coastlines and the extent of the Solomon Islands.
    sub_ax.add_feature(cfeature.LAND)
    sub_ax.coastlines()
    extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3])
    sub_ax.add_geometries([extent_box],
                          ccrs.PlateCarree(),
                          color='none',
                          edgecolor='blue',
                          linewidth=2)

    plt.show()
コード例 #13
0
def load_profile(fname):
    """
    Load the data in the file "fname"

    RETURNS
    xy:     x and y coordinates of the profile (longitude and latitude)
    d   :   Acumulated distance between points in the profile
    z   :   Gravitacional anomaly
    """
    # load data
    data = np.loadtxt(fname, skiprows=4).T

    # perfil representatitvo
    popt, pcov = curve_fit(recta, data[0], data[1])
    xyz = (data[0], recta(data[0], popt[0], popt[1]), data[3])

    # calculates the distance between points
    d = [
        np.sqrt(((xyz[0][x] - xyz[0][x + 1])**2) +
                ((xyz[1][x] - xyz[1][x + 1])**2))
        for x in range(len(xyz[1]) - 1)
    ]
    d = np.hstack(([0], d))

    # calculate the acumulated distnace between points
    for di in range(len(d) - 1):
        d[di + 1] = d[di] + d[di + 1]

    # #################################################################
    # Figures:
    # 01. Map with the profile from the data and the new
    # 02. Topography profile
    # 03. Regional Map with the position of the profile
    # #################################################################
    tiler = StamenTerrain()
    f0 = plt.subplots(figsize=(15, 15))
    grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
    ax01 = plt.subplot(grid[0, :2],
                       projection=ccrs.UTM(zone=19, southern_hemisphere=True))
    ax01.plot(data[0], data[1], 'bo-', label='data and stations position')
    ax01.plot(xyz[0],
              xyz[1],
              'ro-',
              label='my profile and stations projection')

    ax01_latmin_m = data[1].min() - 500
    ax01_latmax_m = data[1].max() + 500
    ax01_lonmin_m = data[0].min() - 1000
    ax01_lonmax_m = data[0].max() + 1000
    ax01.set_extent(
        (ax01_lonmin_m, ax01_lonmax_m, ax01_latmin_m, ax01_latmax_m),
        crs=ccrs.UTM(zone=19, southern_hemisphere=True))

    plt.tick_params(bottom=True,
                    top=True,
                    left=True,
                    right=True,
                    labelbottom=True,
                    labeltop=False,
                    labelleft=True,
                    labelright=False)

    ax01.xaxis.set_visible(True)
    ax01.yaxis.set_visible(True)
    ax01.grid(True)
    ax01.set_title('')
    ax01.set_xlabel('meters')
    ax01.set_ylabel('meters')

    ax02 = plt.subplot(grid[1, :2])
    ax02.plot(d, xyz[2], 'k-')
    ax02.plot(d, xyz[2], 'ko')
    ax02.set_xlabel('distance from the start of the profile (meters)')
    ax02.set_ylabel('altitude (meters)')

    ax02.set_title('Topography through the profile')

    ax03 = plt.subplot(grid[:, 2],
                       projection=ccrs.UTM(zone=19, southern_hemisphere=True))
    ax03_latmin_m = data[1].min() - 700000
    ax03_latmax_m = data[1].max() + 700000
    ax03_lonmin_m = data[0].min() - 300000
    ax03_lonmax_m = data[0].max() + 300000
    ax03.set_extent(
        (ax03_lonmin_m, ax03_lonmax_m, ax03_latmin_m, ax03_latmax_m),
        crs=ccrs.UTM(zone=19, southern_hemisphere=True))
    ax03.plot(data[0][0], data[1][0], 'ko', label='Ubication')
    ax03.coastlines(resolution='10m')
    ax03.add_image(tiler, 6)

    plt.tick_params(bottom=True,
                    top=True,
                    left=True,
                    right=True,
                    labelbottom=True,
                    labeltop=False,
                    labelleft=True,
                    labelright=False)
    ax03.xaxis.set_visible(True)
    ax03.yaxis.set_visible(True)
    ax03.grid(True)

    ax01.legend()
    ax02.legend()
    ax03.legend()

    return f0, xyz, d, data[4]
コード例 #14
0
ファイル: fig1.py プロジェクト: ashindin/multipoint_airglow
from cartopy.io.img_tiles import StamenTerrain


# In[3]:

# from cartopy.feature import NaturalEarthFeature, COLORS


# In[4]:

import cartopy.io.img_tiles as cimgt


# In[5]:

stamen_terrain = StamenTerrain()


# In[13]:

# def scale_bar(ax, length, location=(0.5, 0.05), linewidth=3):
#     """
#     ax is the axes to draw the scalebar on.
#     location is center of the scalebar in axis coordinates ie. 0.5 is the middle of the plot
#     length is the length of the scalebar in km.
#     linewidth is the thickness of the scalebar.
#     """
#     #Projection in metres, need to change this to suit your own figure
#     utm = ccrs.UTM(36)
#     #Get the extent of the plotted area in coordinates in metres
#     x0, x1, y0, y1 = ax.get_extent(utm)
コード例 #15
0
# In[64]:

for month in range(1, 13):
    print(month)
    column = "ws_s_month_Y2014M%02.d" % (month)
    outputFileName = "%sV%0.2d.png" % (column, OUTPUT_VERSION)
    outputFilePath = os.path.join(EC2_OUTPUT_PATH, outputFileName)

    fig = plt.figure(figsize=(16, 9))
    ax = plt.axes(projection=ccrs.Mercator())
    extents = [x0, x1, y0, y1]
    ax.set_extent(extents, crs=None)
    #ax.coastlines(resolution='50m',alpha=1)

    tiler = StamenTerrain()
    mercator = tiler.crs
    ax.add_image(tiler, 6)

    ax.set_xmargin(0.00)
    ax.set_ymargin(0.00)

    for index, row in gdf01.iterrows():
        BWSvalue = row[column]
        facecolor, edgecolor, alpha = categorizeBWS_s(BWSvalue, COLUMN,
                                                      categories)
        if row["aridAndLowWW_month_Y2014M%0.2d" % (month)]:
            facecolor = "#808080"

        feature = ShapelyFeature([row.geometry],
                                 ccrs.PlateCarree(),