plot shapefile city borders on top of cartopy map

  • Last Update :
  • Techknowledgy :

The proper EPSG (European Petroleum Survey Group?) code can be found in one of the .xml files included with the shapefile:

   <gco:CharacterString>26910</gco:CharacterString>
   </code>
   <codeSpace>
      <gco:CharacterString>EPSG</gco:CharacterString>

and passing this as the second parameter in ShapelyFeature() is all it takes to get the shapefile to plot the city borders properly:

# Add city borders
filename = r './shapefile/ba_cities.shp'
shape_feature = ShapelyFeature(Reader(filename).geometries(), ccrs.epsg(26910),
   linewidth = 1, facecolor = (1, 1, 1, 0),
   edgecolor = (0.5, 0.5, 0.5, 1))
ax.add_feature(shape_feature)
plt.show()

Suggestion : 2

I'm trying to plot the outline of Bay Area anycodings_matplotlib city/town borders on top of a cartopy anycodings_matplotlib terrain map using a shapefile obtained here anycodings_matplotlib and following this example. For some reason, anycodings_matplotlib the borders don't show up, even when I anycodings_matplotlib specify borders are on top via zorder. Am I anycodings_matplotlib missing something?,and passing this as the second parameter anycodings_python in ShapelyFeature() is all it takes to anycodings_python get the shapefile to plot the city anycodings_python borders properly:,Trying to figure out a script to stop a process under a specific user over the local network using powershell,The proper EPSG (European Petroleum anycodings_python Survey Group?) code can be found in one anycodings_python of the .xml files included with the anycodings_python shapefile:

I'm trying to plot the outline of Bay Area anycodings_matplotlib city/town borders on top of a cartopy anycodings_matplotlib terrain map using a shapefile obtained here anycodings_matplotlib and following this example. For some reason, anycodings_matplotlib the borders don't show up, even when I anycodings_matplotlib specify borders are on top via zorder. Am I anycodings_matplotlib missing something?

#
import functions
import matplotlib.pyplot as plt
import cartopy.io.img_tiles as cimgt
import cartopy.crs as ccrs
from cartopy.io.shapereader
import Reader
from cartopy.feature
import ShapelyFeature

# Create a Stamen terrain background instance
stamen_terrain = cimgt.Stamen('terrain-background')
fig = plt.figure(figsize = (10, 10))
ax = fig.add_subplot(1, 1, 1, projection = stamen_terrain.crs)

# Set range of map, stipulate zoom level
ax.set_extent([-122.7, -121.5, 37.15, 38.15], crs = ccrs.Geodetic())
ax.add_image(stamen_terrain, 12, zorder = 0)

# Add city borders - not working
filename = r './shapefile/ba_cities.shp'
# from https: //earthworks.stanford.edu/catalog/stanford-vj593xs7263
   shape_feature = ShapelyFeature(Reader(filename).geometries(), ccrs.PlateCarree(), edgecolor = 'black')
ax.add_feature(shape_feature, zorder = 1)
plt.show()

The proper EPSG (European Petroleum anycodings_python Survey Group?) code can be found in one anycodings_python of the .xml files included with the anycodings_python shapefile:

   <gco:CharacterString>26910</gco:CharacterString>
   </code>
   <codeSpace>
      <gco:CharacterString>EPSG</gco:CharacterString>

and passing this as the second parameter anycodings_python in ShapelyFeature() is all it takes to anycodings_python get the shapefile to plot the city anycodings_python borders properly:

# Add city borders
filename = r './shapefile/ba_cities.shp'
shape_feature = ShapelyFeature(Reader(filename).geometries(), ccrs.epsg(26910),
   linewidth = 1, facecolor = (1, 1, 1, 0),
   edgecolor = (0.5, 0.5, 0.5, 1))
ax.add_feature(shape_feature)
plt.show()

Suggestion : 3

Since both quiver() and barbs() are visualisations which draw every vector supplied, there is an additional option to “regrid” the vector field into a regular grid on the target projection (done via cartopy.vector_transform.vector_scalar_to_grid()). This is enabled with the regrid_shape keyword and can have a massive impact on the effectiveness of the visualisation:,Cartopy comes with powerful vector field plotting functionality. There are 3 distinct options for visualising vector fields: quivers (example), barbs (example) and streamplots (example) each with their own benefits for displaying certain vector field forms.,More advanced mapping with cartopy and matplotlib Contour plots Block plots Images Vector plotting ,Cartopy matplotlib integration reference document

import os
import matplotlib.pyplot as plt
from netCDF4
import Dataset as netcdf_dataset
import numpy as np

from cartopy
import config
import cartopy.crs as ccrs

# get the path of the file.It can be found in the repo data directory.
fname = os.path.join(config["repo_data_dir"],
   'netcdf', 'HadISST1_SST_update.nc'
)

dataset = netcdf_dataset(fname)
sst = dataset.variables['sst'][0,: ,: ]
lats = dataset.variables['lat'][: ]
lons = dataset.variables['lon'][: ]

ax = plt.axes(projection = ccrs.PlateCarree())

plt.contourf(lons, lats, sst, 60,
   transform = ccrs.PlateCarree())

ax.coastlines()

plt.show()
import iris
import matplotlib.pyplot as plt

import cartopy.crs as ccrs

# load some sample iris data
fname = iris.sample_data_path('rotated_pole.nc')
temperature = iris.load_cube(fname)

# iris comes complete with a method to put bounds on a simple point
# coordinate.This is very useful...
   temperature.coord('grid_latitude').guess_bounds()
temperature.coord('grid_longitude').guess_bounds()

# turn the iris Cube data structure into numpy arrays
gridlons = temperature.coord('grid_longitude').contiguous_bounds()
gridlats = temperature.coord('grid_latitude').contiguous_bounds()
temperature = temperature.data

# set up a map
ax = plt.axes(projection = ccrs.PlateCarree())

# define the coordinate system that the grid lons and grid lats are on
rotated_pole = ccrs.RotatedPole(pole_longitude = 177.5, pole_latitude = 37.5)
plt.pcolormesh(gridlons, gridlats, temperature, transform = rotated_pole)

ax.coastlines()

plt.show()
import os
import matplotlib.pyplot as plt

from cartopy
import config
import cartopy.crs as ccrs

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

# get the path of the file.It can be found in the repo data directory.
fname = os.path.join(config["repo_data_dir"],
   'raster', 'sample', 'Miriam.A2012270.2050.2km.jpg'
)
img_extent = (-120.67660000000001, -106.32104523100001, 13.2301484511245, 30.766899999999502)
img = plt.imread(fname)

ax = plt.axes(projection = ccrs.PlateCarree())
plt.title('Hurricane Miriam from the Aqua/MODIS satellite\n'
   '2012 09/26/2012 20:50 UTC')

# set a margin around the data
ax.set_xmargin(0.05)
ax.set_ymargin(0.10)

# add the image.Because this image was a tif, the "origin" of the image is in the
# upper left corner
ax.imshow(img, origin = 'upper', extent = img_extent, transform = ccrs.PlateCarree())
ax.coastlines(resolution = '50m', color = 'black', linewidth = 1)

# mark a known place to help us geo - locate ourselves
ax.plot(-117.1625, 32.715, 'bo', markersize = 7, transform = ccrs.Geodetic())
ax.text(-117, 33, 'San Diego', transform = ccrs.Geodetic())

plt.show()
import matplotlib.pyplot as plt
import numpy as np

import cartopy
import cartopy.crs as ccrs

def sample_data(shape = (20, 30)):
   ""
"
Returns ``(x, y, u, v, crs)`` of some vector data
computed mathematically.The returned crs will be a rotated
pole CRS, meaning that the vectors will be unevenly spaced in
   regular PlateCarree space.

""
"
crs = ccrs.RotatedPole(pole_longitude = 177.5, pole_latitude = 37.5)

x = np.linspace(311.9, 391.1, shape[1])
y = np.linspace(-23.6, 24.8, shape[0])

x2d, y2d = np.meshgrid(x, y)
u = 10 * (2 * np.cos(2 * np.deg2rad(x2d) + 3 * np.deg2rad(y2d + 30)) ** 2)
v = 20 * np.cos(6 * np.deg2rad(x2d))

return x, y, u, v, crs

def main():
   ax = plt.axes(projection = ccrs.Orthographic(-10, 45))

ax.add_feature(cartopy.feature.OCEAN, zorder = 0)
ax.add_feature(cartopy.feature.LAND, zorder = 0, edgecolor = 'black')

ax.set_global()
ax.gridlines()

x, y, u, v, vector_crs = sample_data()
ax.quiver(x, y, u, v, transform = vector_crs)

plt.show()

if __name__ == '__main__':
   main()
""
"
Regridding vectors with quiver
-- -- -- -- -- -- -- -- -- -- -- -- -- -- --

This example demonstrates the regridding functionality in quiver(there exists equivalent functionality in: meth: `cartopy.mpl.geoaxes.GeoAxes.barbs`).

Regridding can be an effective way of visualising a vector field, particularly
if the data is dense or warped.
""
"
import matplotlib.pyplot as plt
import numpy as np

import cartopy.crs as ccrs

def sample_data(shape = (20, 30)):
   ""
"
Returns ``(x, y, u, v, crs)`` of some vector data
computed mathematically.The returned CRS will be a North Polar
Stereographic projection, meaning that the vectors will be unevenly
spaced in a PlateCarree projection.

""
"
crs = ccrs.NorthPolarStereo()
scale = 1e7
x = np.linspace(-scale, scale, shape[1])
y = np.linspace(-scale, scale, shape[0])

x2d, y2d = np.meshgrid(x, y)
u = 10 * np.cos(2 * x2d / scale + 3 * y2d / scale)
v = 20 * np.cos(6 * x2d / scale)

return x, y, u, v, crs

def main():
   plt.figure(figsize = (8, 10))

x, y, u, v, vector_crs = sample_data(shape = (50, 50))
ax1 = plt.subplot(2, 1, 1, projection = ccrs.PlateCarree())
ax1.coastlines('50m')
ax1.set_extent([-45, 55, 20, 80], ccrs.PlateCarree())
ax1.quiver(x, y, u, v, transform = vector_crs)

ax2 = plt.subplot(2, 1, 2, projection = ccrs.PlateCarree())
plt.title('The same vector field regridded')
ax2.coastlines('50m')
ax2.set_extent([-45, 55, 20, 80], ccrs.PlateCarree())
ax2.quiver(x, y, u, v, transform = vector_crs, regrid_shape = 20)

plt.show()

if __name__ == '__main__':
   main()

Suggestion : 4

overlay features such as administrative borders, rivers, catchments, rain gauges, cities, …,Here, we create a map without radar data to concentrate on the other layers.,Here, we plot countries as patches on a lat/lon (WGS84) map (data from Natural Earth Data again).,We extract features using - the OGR.Layer AttributeFilter and - the wradlib.georef.get_vector_coordinates function.

[1]:
import wradlib as wrl
import matplotlib.pyplot as pl
import warnings

warnings.filterwarnings("ignore")
try:
get_ipython().magic("matplotlib inline")
except:
   pl.ion()
import numpy as np

# Some more matplotlib tools we will need...
   import matplotlib.ticker as ticker
from matplotlib.colors
import LogNorm
from mpl_toolkits.axes_grid1
import make_axes_locatable
import cartopy.crs as ccrs
import cartopy.feature as cfeature
/home/runner / micromamba - root / envs / wradlib - notebooks / lib / python3 .10 / site - packages / tqdm / auto.py: 22: TqdmWarning: IProgress not found.Please update jupyter and ipywidgets.See https: //ipywidgets.readthedocs.io/en/stable/user_install.html
   from.autonotebook
import tqdm as notebook_tqdm
gdalwarp - te 88. 20. 93. 27. srtm_54_07.tif srtm_55_07.tif srtm_54_08.tif srtm_55_08.tif bangladesh.tif
[2]:
def plot_dem(ax):
   filename = wrl.util.get_wradlib_data_file("geo/bangladesh.tif")
ds = wrl.io.open_raster(filename)
# pixel_spacing is in output units(lonlat)
ds = wrl.georef.reproject_raster_dataset(ds, spacing = 0.005)
rastervalues, rastercoords, proj = wrl.georef.extract_raster_dataset(ds)
# specify kwargs
for plotting, using terrain colormap and LogNorm
dem = ax.pcolormesh(
   rastercoords[..., 0],
   rastercoords[..., 1],
   rastervalues,
   cmap = pl.cm.terrain,
   norm = LogNorm(vmin = 1, vmax = 3000),
   transform = ccrs.PlateCarree(),
)
# add colorbar and title
# we use LogLocator
for colorbar
cb = pl.gcf().colorbar(dem, ticks = ticker.LogLocator(subs = range(10)), pad = 0.075)
cb.set_label("terrain height [m]")