Straight line through the pole with Cartopy stereographic projection - matplotlib

I'm using cartopy to produce a map of the Arctic with stereographic projection and then plotting a line (to show the position of a cross-section) over the top. If I use the following code then the line doesn't go in a straight line through the pole but instead goes along a line of latitude.
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
x=[180,0]
y=[50,50]
ax = plt.axes(projection=ccrs.NorthPolarStereo())
ax.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
ax.plot(x,y,transform=ccrs.PlateCarree())
plt.gca().stock_img()
plt.gca().coastlines()
plt.show()
To get round this I have to change x and y to:
x=[180,180,0,0]
y=[50,90,90,50]
so that there are two data points at the North Pole. Is there a better solution for this?
Edit: Image attached
Thanks,
Tim

#ajdawson's answer is correct. Using the Geodetic transform, in this case, will do the trick.
To understand the reason the line wasn't as you expected it to look, we need to understand what the PlateCarree transform represents.
Firstly, lets observe that all lines drawn in the transform=<projection> form, using Cartopy, should pass through the same Geographic points irrespective of the projection that the line is being drawn on.
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def main():
x=[180, 180, 0, 0]
y=[50, 90, 90, 50]
# plot2 - North Polar Stereographic
ax = plt.subplot(211, projection=ccrs.NorthPolarStereo())
ax.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
ax.plot(x, y, transform=ccrs.PlateCarree(), color='red', lw=2)
ax.stock_img()
ax.coastlines()
# plot2 - PlateCarree
ax = plt.subplot(212, projection=ccrs.PlateCarree(central_longitude=45))
ax.set_extent([0, 360, -45, 90], crs=ccrs.PlateCarree())
ax.plot(x, y, transform=ccrs.PlateCarree(), color='red', lw=2)
ax.stock_img()
ax.coastlines()
plt.show()
if __name__ == '__main__':
main()
So going back to drawing your original coordinates (which were in PlateCarree coordinates) on a PlateCarree map:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def main():
x=[180, 0]
y=[50, 50]
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=45))
ax.set_extent([0, 360, -45, 90], crs=ccrs.PlateCarree())
ax.plot(x, y, transform=ccrs.PlateCarree(), color='red', lw=2)
ax.stock_img()
ax.coastlines()
plt.tight_layout()
plt.show()
if __name__ == '__main__':
main()
You will find that the line passes through the same geographic points as your bad line in the original question.
This should satisfy you that Cartopy is behaving rationally and it is not a bug, but it doesn't answer the question about how you would go about drawing the line you desire.
#ajdawson has already said that, in your case, drawing the line:
plt.plot([180, 0], [50, 50] , transform=ccrs.Geodetic())
will result in the desired output.
That is because the Geodetic coordinate reference system draws the line of shortest distance on the globe between two points. However, there will be a latitude which, when crossed, passing through the north pole does not provide the shortest distance:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def main():
ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=45))
ax.set_global()
ax.plot([180, 0], [20, 20], transform=ccrs.Geodetic(), color='red', lw=2, label='Latitude = 20')
ax.plot([180, 0], [0, 0], transform=ccrs.Geodetic(), color='blue', lw=2, label='Latitude = 0')
ax.plot([180, 0], [-20, -20], transform=ccrs.Geodetic(), color='yellow', lw=2, label='Latitude = -20')
ax.outline_patch.set_zorder(2)
plt.legend(loc=8, bbox_to_anchor=(0.65, -0.2), shadow=True, fancybox=True)
ax.stock_img()
ax.coastlines()
plt.tight_layout()
plt.show()
if __name__ == '__main__':
main()
Generally, if you wanted to draw a Geodetic line which always crosses the North Pole, then the north pole should be one of the coordinates of the line.
plt.plot([180, 0, 0], [-45, 90, -45] , transform=ccrs.Geodetic())
Finally, just to throw it into the mix, if you just wanted a vertical line in a North Polar Stereographic projection which crosses the North Pole, it is worth remembering that there exists a Cartesian coordinate system (in which it is worth remembering that the numbers are not latitude and longitudes), so simply doing:
ax = plt.axes(projection=ccrs.NorthPolarStereo())
plt.axvline()
Will also do the trick! (but is less transferable than the Geodetic approach)
Wow, my answer got long. I hope your still with me and that makes the whole PlateCarree thing clearer!

I think you need to use the Geodetic transform when plotting this section rather than Plate Carree:
<!-- language: lang-py -->
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
x=[180,0]
y=[50,50]
ax = plt.axes(projection=ccrs.NorthPolarStereo())
ax.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
ax.plot(x,y,transform=ccrs.Geodetic())
ax.stock_img()
ax.coastlines()
plt.show()
The result looks like this:
I think that is the correct way to handle this anyway!
Andrew

Related

How to apply Earth Features and Land/Ocean masks in high resolution coastlines in Cartopy?

I am using the coastlines of the GSHHS dataset in Cartopy. This has a high resolution for coastlines. But I want to not only plot the high resolution coastline but also apply a mask for the ocean.
import matplotlib.pyplot as plt
import cartopy
fig = plt.figure(figsize=(20,12))
ax = plt.axes(projection=cartopy.crs.PlateCarree())
coast = cartopy.feature.GSHHSFeature(scale="full")
ax.add_feature(coast, linewidth=2)
ax.add_feature(cartopy.feature.NaturalEarthFeature("physical", "land", "10m"))
ax.set_extent([-17, -16, 27.9, 28.7])
Executing the code there're differences in the images, since I guess that ax.add_feature(cartopy.feature.NaturalEarthFeature("physical", "land", "10m")) is using the "10m" resolution, while GSHHS has a higher resolution.
How can I mask using GSHHS higher resolution? Thx.
Before one can answer the question how to apply a mask to hide features in the main plot, we need to investigate the available masks first.
In our case, the main plot is Natural_Earth 10m resolution Physical Land features, and various resolutions of GSHHSFeature as the available masks.
The code and the output plot below reveals the insight.
# Code adapted from:-
# Src: https://ctroupin.github.io/posts/2019-09-02-fine-coast/
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
resolutions = {"c": "crude",
"l": "low",
"i": "intermediate",
"h": "high",
"f": "full"}
coordinates = (8.7, 8.81, 42.55, 42.60)
myproj = ccrs.PlateCarree()
fig = plt.figure(figsize=(8, 4))
for i, res in enumerate(resolutions):
ax = plt.subplot(2, 3, i+1, projection=myproj)
coast = cfeature.GSHHSFeature(scale=res)
ax.add_feature(coast, facecolor="lightgray")
ax.add_feature(cartopy.feature.NaturalEarthFeature("physical", "land", "10m"),
ec="red", fc="yellow", lw=2, alpha=0.4)
ax.set_xlim(coordinates[0], coordinates[1])
ax.set_ylim(coordinates[2], coordinates[3])
plt.title(resolutions[res])
plt.suptitle("GSHHS: gray Versus 10m_Physical_Land: yellow/red")
plt.show()
Suppose we need a plot at this zoom level. It is clearly that the outlines from 2 data sources do not fit well enough to the eyes of the viewers. We may conclude that none of the available masks is fit for the target plot.
But if the plot extents is wider, or smaller scale plots, coupled with some cartographic techniques, e.g. using thicker coastlines, one may get acceptable plots. The process is trial-and-error approach.
Edit1
With (Global_land_mask) added, more choices can be plotted for
comparison.
from global_land_mask import globe
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np
# Extent of map in degrees
minlon,maxlon,minlat,maxlat = (8.7, 8.81, 42.55, 42.60)
# Lat/lon points to get for `global_land_mask` uses
# Finer than 500x250 has no improvement
lons = np.linspace(minlon,maxlon, 500)
lats = np.linspace(minlat,maxlat, 250)
# Make a grid
lon_grid, lat_grid = np.meshgrid(lons,lats)
# Get whether the points are on land.
z = globe.is_land(lat_grid, lon_grid)
# GSHHS ...
resolutions = {"c": "crude",
"l": "low",
"i": "intermediate",
"h": "high",
"f": "full"}
myproj = ccrs.PlateCarree()
fig = plt.figure(figsize=(8, 4))
for i, res in enumerate(resolutions):
ax = plt.subplot(2, 3, i+1, projection=myproj)
# GSHHSFeature
coast = cfeature.GSHHSFeature(scale=res)
ax.add_feature(coast, facecolor="brown", alpha=0.5)
# 10m physical_land
ax.add_feature(cfeature.NaturalEarthFeature("physical", "land", "10m"),
ec="red", fc="yellow", lw=2, alpha=0.4)
# Global_land_mask data is used to create fillcontour
# The fillcontour with proper (colormap, zorder, alpha) can be used as land `mask`
ax.contourf(lon_grid, lat_grid, z, cmap="Greys_r", alpha=0.4)
ax.set_xlim(minlon, maxlon)
ax.set_ylim(minlat, maxlat)
plt.title(resolutions[res])
plt.suptitle("GSHHS:brown/black | 10m_Land:yellow/red | Global_land_mask:light_gray")
plt.show()
# The best resolutuion from `Global_land_mask` is plotted in `lightgray` covering the sea areas

Unexpected behavior from Cartopy

I'm trying to draw a 'straight' line on the surface of the Earth (a great circle), which should appear curved on an orthographic projection that isn't looking straight down on the curve. However, when I try to connect two points with a geodetic line in cartopy I get a line with a kink in it. Where is this kink coming from? And how can I get a correctly rendered great circle segment?
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
lats = [0, 36]
lons = [15, 76]
ax = plt.axes(projection = ccrs.Orthographic(central_longitude=0, central_latitude=45))
ax.plot(lons, lats, transform=ccrs.Geodetic())
ax.set_global()
ax.gridlines()
From the option transform=ccrs.Geodetic(), the implication is that you need great-circle arc as a result of your ax.plot() statement.
Without proper setting of projection._threshold you will get the kinked line as you experienced.
Here is the modified code and the expected result.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
lats = [0, 36]
lons = [15, 76]
myProj = ccrs.Orthographic(central_longitude=0, central_latitude=45)
myProj._threshold = myProj._threshold/20.
ax = plt.axes(projection = myProj)
ax.plot(lons, lats, transform=ccrs.Geodetic())
ax.set_global()
ax.gridlines()
Smaller values of the threshold will cause the plotted lines to have denser vertices along the lines. Additional vertices are not obtained by simple interpolation when great-circle arcs are required in this case.

Limit extent of orthograpic projection (zooming)

I would like to produce orthographic (polar) plots of Antarctica that are 'zoomed' with respect to the default settings. By default I get this:
Antarctica polar
The following script produced this.
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
ax = plt.axes(projection=ccrs.Orthographic(central_longitude=0.0, central_latitude=-90.))
ax.stock_img()
plt.show()
My best attempt to tell Cartopy 'limit the latitude to 60S to 90S' was:
ax.set_extent([-180,180,-60,-90], ccrs.PlateCarree())
unfortunately it does not give the desired result. Any ideas? Thanks in advance.
I'm not sure I fully understand what you're trying to do. Your example looks like a bounding box that was defined, but you'd like it rounded like your first example?
cartopy documentation has an example of this http://scitools.org.uk/cartopy/docs/latest/examples/always_circular_stereo.html:
import matplotlib.path as mpath
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature
def main():
fig = plt.figure(figsize=[10, 5])
ax1 = plt.subplot(1, 2, 1, projection=ccrs.SouthPolarStereo())
ax2 = plt.subplot(1, 2, 2, projection=ccrs.SouthPolarStereo(),
sharex=ax1, sharey=ax1)
fig.subplots_adjust(bottom=0.05, top=0.95,
left=0.04, right=0.95, wspace=0.02)
# Limit the map to -60 degrees latitude and below.
ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())
ax1.add_feature(cartopy.feature.LAND)
ax1.add_feature(cartopy.feature.OCEAN)
ax1.gridlines()
ax2.gridlines()
ax2.add_feature(cartopy.feature.LAND)
ax2.add_feature(cartopy.feature.OCEAN)
# Compute a circle in axes coordinates, which we can use as a boundary
# for the map. We can pan/zoom as much as we like - the boundary will be
# permanently circular.
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax2.set_boundary(circle, transform=ax2.transAxes)
plt.show()
if __name__ == '__main__':
main()

How to plot a tissot with cartopy and matplotlib?

For plotting skymaps I just switched from Basemap to cartopy, I like it a lot more
.
(The main reason was segfaulting of Basemap on some computers, which I could not fix).
The only thing I struggle with, is getting a tissot circle (used to show the view cone of our telescope.)
This is some example code plotting random stars (I use a catalogue for the real thing):
import matplotlib.pyplot as plt
from cartopy import crs
import numpy as np
# create some random stars:
n_stars = 100
azimuth = np.random.uniform(0, 360, n_stars)
altitude = np.random.uniform(75, 90, n_stars)
brightness = np.random.normal(8, 2, n_stars)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection=crs.NorthPolarStereo())
ax.background_patch.set_facecolor('black')
ax.set_extent([-180, 180, 75, 90], crs.PlateCarree())
plot = ax.scatter(
azimuth,
altitude,
c=brightness,
s=0.5*(-brightness + brightness.max())**2,
transform=crs.PlateCarree(),
cmap='gray_r',
)
plt.show()
How would I add a tissot circle with a certain radius in degrees to that image?
https://en.wikipedia.org/wiki/Tissot%27s_indicatrix
I keep meaning to go back and add the two functions from GeographicLib which provide the forward and inverse geodesic calculations, with this it is simply a matter of computing a geodetic circle by sampling at appropriate azimuths for a given lat/lon/radius. Alas, I haven't yet done that, but there is a fairly primitive (but effective) wrapper in pyproj for the functionality.
To implement a tissot indicatrix then, the code might look something like:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np
from pyproj import Geod
import shapely.geometry as sgeom
def circle(geod, lon, lat, radius, n_samples=360):
"""
Return the coordinates of a geodetic circle of a given
radius about a lon/lat point.
Radius is in meters in the geodetic's coordinate system.
"""
lons, lats, back_azim = geod.fwd(np.repeat(lon, n_samples),
np.repeat(lat, n_samples),
np.linspace(360, 0, n_samples),
np.repeat(radius, n_samples),
radians=False,
)
return lons, lats
def main():
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
geod = Geod(ellps='WGS84')
radius_km = 500
n_samples = 80
geoms = []
for lat in np.linspace(-80, 80, 10):
for lon in np.linspace(-180, 180, 7, endpoint=False):
lons, lats = circle(geod, lon, lat, radius_km * 1e3, n_samples)
geoms.append(sgeom.Polygon(zip(lons, lats)))
ax.add_geometries(geoms, ccrs.Geodetic(), facecolor='blue', alpha=0.7)
plt.show()
if __name__ == '__main__':
main()

central longitude for NorthPolarStereo

I'd like to plot a polar stereographic plot of the Northern Hemisphere with 180 at the bottom of the plot so I can emphasize the Pacific region. I'm using the latest cartopy from git, and can make a polar stereographic plot no problem, but I can't work out how to change which longitude is at the bottom of the plot. I tried setting the longitude extent to [-180, 180] but this doesn't help, and the NorthPolarStereo() doesn't accept any keyword arguments like central_longitude. Is this possible currently?
This feature has now been implemented in Cartopy (v0.6.x). The following example produces two subplots in Northern Hemisphere polar stereographic projections, one with the default settings and one with the central longitude changed:
"""Stereographic plot with adjusted central longitude."""
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.examples.waves import sample_data
# read sample data
x, y, z = sample_data(shape=(73, 145))
fig = plt.figure(figsize=(8, 4))
# first plot with default settings
ax1 = fig.add_subplot(121, projection=ccrs.NorthPolarStereo())
cs1 = ax1.contourf(x, y, z, 50, transform=ccrs.PlateCarree(),
cmap='gist_ncar')
ax1.set_extent([0, 360, 0, 90], crs=ccrs.PlateCarree())
ax1.coastlines()
ax1.set_title('Centred on 0$^\circ$ (default)')
# second plot with 90W at the bottom of the plot
ax2 = fig.add_subplot(
122, projection=ccrs.NorthPolarStereo(central_longitude=-90))
cs2 = ax2.contourf(x, y, z, 50, transform=ccrs.PlateCarree(),
cmap='gist_ncar')
ax2.set_extent([0, 360, 0, 90], crs=ccrs.PlateCarree())
ax2.coastlines()
ax2.set_title('Centred on 90$^\circ$W')
plt.show()
The output of this script is:
For Cartopy 0.17 and matplotlib 3.1.1 (Python 3.7), I got an error in set_extent() with the above solution.
It seems that set_extent() only works this way:
ax1.set_extent([-180, 180, 0, 90], crs=ccrs.PlateCarree())
ax2.set_extent([-179, 179, 0, 90], crs=ccrs.PlateCarree())
So, the rotated image needs some weird longitude boundaries..