Adding a further requirement to this question, I also need to have the oceans in blue (or any other colour).
For the 'PlateCarree' projection I can simply do this
crs = ccrs.PlateCarree()
crs_proj4 = crs.proj4_init
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
w = world.to_crs(crs_proj4)
g = w.plot(facecolor='sandybrown', edgecolor='black')
And now adding the ocean colour
g.set_facecolor('#A8C5DD')
If I now want to use a polar stereographic peojection
ccrs.NorthPolarStereo()
or
ccrs.SouthPolarStereo()
the projection does not work. When applying the answer to this question, I cannot get the oceans coloured
You need to plot the map geometries on Cartopy geoaxes, and use cartopy.feature.OCEAN to plot the ocean. Here is the working code that you may try. Read the comments in the code for clarification.
import geopandas as gpd
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy
facecolor = 'sandybrown'
edgecolor = 'black'
ocean_color = '#A8C5DD'
#crs1 = ccrs.SouthPolarStereo()
crs1 = ccrs.NorthPolarStereo()
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
w1 = world.to_crs(crs1.proj4_init)
fig1, ax1 = plt.subplots(figsize=(7,7), subplot_kw={'projection': crs1})
# useful code to set map extent,
# --- if you want maximum extent, comment out the next line of code ---
ax1.set_extent([-60.14, 130.4, -13.12, -24.59], crs=ccrs.PlateCarree())
# at maximum extent, the circular bound trims map features nicely
ax1.add_geometries(w1['geometry'], crs=crs1, \
facecolor=facecolor, \
edgecolor=edgecolor, \
linewidth=0.5)
# this adds the ocean coloring
ax1.add_feature(cartopy.feature.OCEAN, facecolor=ocean_color, edgecolor='none')
plt.show()
The output plot will be:
Related
I want to mark some location (lat,lon) on a cartopy map by a small image/icon. how can I do that ?
import cartopy.crs as crs
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 5))
ax = plt.axes(projection=crs.PlateCarree())
ax.stock_img()
img = plt.imread('flag.png') #the image I want to add on the map
plt.show()
I found a source here: https://gist.github.com/secsilm/37db690ab9716f768d1a1e43d3f53e3f
But it doesn't work for me, the map show up without any flag. Is there any other way to do that ?
Thank a lot!.
The following worked just fine for me:
import matplotlib.pyplot as plt
import cartopy.crs as crs
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
# Read image
lat = 39
lon = -95
img = plt.imread('/Users/rmay/Downloads/flag.png')
# Plot the map
fig = plt.figure(figsize=(10, 5))
ax = plt.axes(projection=crs.PlateCarree())
ax.coastlines()
ax.stock_img()
# Use `zoom` to control the size of the image
imagebox = OffsetImage(img, zoom=.1)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, [lon, lat], pad=0, frameon=False)
ax.add_artist(ab)
You might want to try debugging by changing zoom to larger values or setting frameon to True. If you have further problem, be sure to post your values for lon/lat.
I tried the code in the gist you linked as it uses cartopy to georeference the image. I got the following result:
world map with china flag
Is this the effect you desired? The only thing I changed in the code copied from the gist is the picture. I used this one
I'm looking to overlay some coastlines on graph representing an area. The area is defined by the box:
Top: 3900000
Bottom: 3450000
Left: 300000
Right: 800000
with the coordinate system WGS_1984_UTM_Zone_36N.
I've tried using mpl_toolkits.basemap however I can't work out how to specify that area as the ESPG code (32636) is not accepted by Basemap, and when I attempt to manually insert the projection parameters (m = Basemap(projection='tmerc', k_0=0.9996, lat_0=0, lon_0=33, llcrnrx=300000, llcrnry=3450000, urcrnrx=800000, urcrnry=3900000) it still requires a lat long boundary box.
Is there a another way to define that area in Basemap?
Thanks!
Edit: I'm trying to return an area of coastline defined by a box that is in the utm system, using lat/long values for the extremities of the box would result in over/underlap of the area covered by the coastlines when converted back into the utm system (I think, please correct me if I'm wrong).
Try cartopy and its new epsg feature:
projection = ccrs.epsg(32636)
fig, ax = plt.subplots(figsize=(5, 5),
subplot_kw=dict(projection=projection))
ax.coastlines(resolution='10m')
Here is a notebook with an example:
http://nbviewer.ipython.org/gist/ocefpaf/832cf7917c21da229564
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# make sure the value of resolution is a lowercase L,
# for 'low', not a numeral 1
map = Basemap(projection='merc', lat_0=57, lon_0=-135,
resolution = 'h', area_thresh = 0.1,
llcrnrlon=-136.25, llcrnrlat=56,
urcrnrlon=-134.25, urcrnrlat=57.75)
map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='coral')
map.drawmapboundary()
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))
plt.show()
All at this link https://peak5390.wordpress.com/2012/12/08/matplotlib-basemap-tutorial-making-a-simple-map/
I am trying to use streamplot function to plot wind field with basemap, projection "ortho". My test code is mainly based on this example:
Plotting wind vectors and wind barbs
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
import datetime
from mpl_toolkits.basemap import Basemap, shiftgrid
from Scientific.IO.NetCDF import NetCDFFile as Dataset
# specify date to plot.
yyyy=1993; mm=03; dd=14; hh=00
date = datetime.datetime(yyyy,mm,dd,hh)
# set OpenDAP server URL.
URLbase="http://nomads.ncdc.noaa.gov/thredds/dodsC/modeldata/cmd_pgbh/"
URL=URLbase+"%04i/%04i%02i/%04i%02i%02i/pgbh00.gdas.%04i%02i%02i%02i.grb2" %\
(yyyy,yyyy,mm,yyyy,mm,dd,yyyy,mm,dd,hh)
data = Dataset(URL)
#data = netcdf.netcdf_file(URL)
# read lats,lons
# reverse latitudes so they go from south to north.
latitudes = data.variables['lat'][:][::-1]
longitudes = data.variables['lon'][:].tolist()
# get wind data
uin = data.variables['U-component_of_wind_height_above_ground'][:].squeeze()
vin = data.variables['V-component_of_wind_height_above_ground'][:].squeeze()
# add cyclic points manually (could use addcyclic function)
u = np.zeros((uin.shape[0],uin.shape[1]+1),np.float64)
u[:,0:-1] = uin[::-1]; u[:,-1] = uin[::-1,0]
v = np.zeros((vin.shape[0],vin.shape[1]+1),np.float64)
v[:,0:-1] = vin[::-1]; v[:,-1] = vin[::-1,0]
longitudes.append(360.); longitudes = np.array(longitudes)
# make 2-d grid of lons, lats
lons, lats = np.meshgrid(longitudes,latitudes)
# make orthographic basemap.
m = Basemap(resolution='c',projection='ortho',lat_0=60.,lon_0=-60.)
# create figure, add axes
fig1 = plt.figure(figsize=(8,10))
ax = fig1.add_axes([0.1,0.1,0.8,0.8])
# define parallels and meridians to draw.
parallels = np.arange(-80.,90,20.)
meridians = np.arange(0.,360.,20.)
# first, shift grid so it goes from -180 to 180 (instead of 0 to 360
# in longitude). Otherwise, interpolation is messed up.
ugrid,newlons = shiftgrid(180.,u,longitudes,start=False)
vgrid,newlons = shiftgrid(180.,v,longitudes,start=False)
# now plot.
lonn, latt = np.meshgrid(newlons, latitudes)
x, y = m(lonn, latt)
st = plt.streamplot(x, y, ugrid, vgrid, color='r', latlon='True')
# draw coastlines, parallels, meridians.
m.drawcoastlines(linewidth=1.5)
m.drawparallels(parallels)
m.drawmeridians(meridians)
# set plot title
ax.set_title('SLP and Wind Vectors '+str(date))
plt.show()
After running the code, I got a blank map with a red smear in the lower left corner (please see the figure). After zoom this smear out, I can see the wind stream in a flat projection (not in "ortho" projection) So I guess this is the problem of data projection on the map. I did tried function transform_vector but it does not solve the problem Can anybody tell me, what did I do wrong, please! Thank you.
A new map after updating code:
You are plotting lat/lon coordinates on a map with an orthographic projection. Normally you can fix this by changing your plotting command to:
m.streamplot(mapx, mapy, ugrid, vgrid, color='r', latlon=True)
But your coordinate arrays don't have the same dimensions, that needs to be fixed as well.
I want to plot a graph on a map where the nodes would be defined by coordinates (lat, long) and have some value associated.
I have been able to plot points as a scatterplot on a basemap but can't seem to find how to plot a graph on the map.
Thanks.
EDIT: I have added code on how I plotted the points on a basemap. Most of it has been adapted from code in this article.
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Point, MultiPoint
import pandas as pd
import matplotlib.pyplot as plt
m = Basemap(
projection='merc',
ellps = 'WGS84',
llcrnrlon=-130,
llcrnrlat=25,
urcrnrlon=-60,
urcrnrlat=50,
lat_ts=0,
resolution='i',
suppress_ticks=True)
# Create Point objects in map coordinates from dataframe lon
# and lat values
# I have a dataframe of coordinates
map_points = pd.Series(
[Point(m(mapped_x, mapped_y))
for mapped_x, mapped_y in zip(df['lon'],
df['lat'])])
amre_points = MultiPoint(list(map_points.values))
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='w', frame_on=False)
fig.set_size_inches(18.5, 10.5)
# Create a scatterplot on the map
dev = m.scatter(
[geom.x for geom in map_points],
[geom.y for geom in map_points],
20, marker='o', lw=.25,
facecolor='#33ccff', edgecolor='w',
alpha=0.9,antialiased=True,
zorder=3)
m.fillcontinents(color='#555555')
I get this image:
Here is one way to do it:
import networkx as nx
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
m = Basemap(
projection='merc',
llcrnrlon=-130,
llcrnrlat=25,
urcrnrlon=-60,
urcrnrlat=50,
lat_ts=0,
resolution='i',
suppress_ticks=True)
# position in decimal lat/lon
lats=[37.96,42.82]
lons=[-121.29,-73.95]
# convert lat and lon to map projection
mx,my=m(lons,lats)
# The NetworkX part
# put map projection coordinates in pos dictionary
G=nx.Graph()
G.add_edge('a','b')
pos={}
pos['a']=(mx[0],my[0])
pos['b']=(mx[1],my[1])
# draw
nx.draw_networkx(G,pos,node_size=200,node_color='blue')
# Now draw the map
m.drawcountries()
m.drawstates()
m.bluemarble()
plt.title('How to get from point a to point b')
plt.show()
As of today there is a nice alternative to basemap. Mplleaflet is a library inspired by mpld3. It plots faster than basemap, is more easy to use and allows to visualizing geographic data on beautiful interactive openstreetmap. The input can be longitude and latitude the library automatically projects the data properly.
Input dictionary pos, where the node (country) is the key and long lat are saved as value.
pos = {u'Afghanistan': [66.00473365578554, 33.83523072784668],
u'Aland': [19.944009818523348, 60.23133494165451],
u'Albania': [20.04983396108883, 41.14244989474517],
u'Algeria': [2.617323009197829, 28.158938494487625],
.....
Plotting is as easy as:
import mplleaflet
fig, ax = plt.subplots()
nx.draw_networkx_nodes(GG,pos=pos,node_size=10,node_color='red',edge_color='k',alpha=.5, with_labels=True)
nx.draw_networkx_edges(GG,pos=pos,edge_color='gray', alpha=.1)
nx.draw_networkx_labels(GG,pos, label_pos =10.3)
mplleaflet.display(fig=ax.figure)
I have some satellite image data I would like to display using Cartopy. I have successfully followed the image example detailed here. Resulting in this code:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
fig = plt.figure(figsize=(12, 12))
img_extent = (-77, -59, 9, 26)
ax = plt.axes(projection=ccrs.PlateCarree())
# image data coming from server, code not shown
ax.imshow(img, origin='upper', extent=img_extent)
ax.set_xmargin(0.05)
ax.set_ymargin(0.10)
# mark a known place to help us geo-locate ourselves
ax.plot(-117.1625, 32.715, 'bo', markersize=7)
ax.text(-117, 33, 'San Diego')
ax.coastlines()
ax.gridlines()
plt.show()
This code generates the following image
My problem is that the satellite image data is not in the PlateCarree projection, but the Mercator projection.
But when I get the axis object with
ax = plt.axes(projection=ccrs.Mercator())
I lose the coastlines.
I saw the issue reported here. But
ax.set_global()
results in this image:
The data is not present, and San Diego is in the wrong location. Also the lat/lon extents have changed. What am I doing wrong?
Post Discussion Update
The main problem is that I had not properly specified the image extents in the target projection with the transform_points method. I also had to be specific about the coordinate reference system in the imshow method as Phil suggests. Here is the correct code:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
proj = ccrs.Mercator()
fig = plt.figure(figsize=(12, 12))
extents = proj.transform_points(ccrs.Geodetic(),
np.array([-77, -59]),
np.array([9, 26]))
img_extents = (extents[0][0], extents[1][0], extents[0][6], extents[1][7] )
ax = plt.axes(projection=proj)
# image data coming from server, code not shown
ax.imshow(img, origin='upper', extent=img_extents,transform=proj)
ax.set_xmargin(0.05)
ax.set_ymargin(0.10)
# 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())
ax.coastlines()
ax.gridlines()
plt.show()
Resulting in this correctly geoprojected satellite image:
Ideally, try to always be specific about the coordinate reference system your data are in when plotting with cartopy (via the transform keyword). This will mean you can just switch projections in your script and the data will automatically be put in the correct place.
So in your case, the plt.imshow should have a transform=ccrs.Mercator() keyword argument (you may need a a more specific parameterised Mercator instance). If your extents are in Geodetic (lats and lons) you will have to transform the bounding box into the mercator coordinates, but other than that, everything else should work as expected.
NOTE: I'm going to go and update the example to include the transform argument ;-) (PR: https://github.com/SciTools/cartopy/pull/343)
HTH