Problem with ortho projection and pcolormesh in matplotlib-basemap - matplotlib

I have trouble with the ortho projection and pcolormesh.
It should plot a mesh of grid points. Instead, in the upper right portion of the sphere it plots strange lines instead of grid points. The mapping of the mesh looks off.
I tried the code below.
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
plt.clf()
dpp =1 # degrees per pixel
lons = np.arange(-180,180+dpp,dpp)
lats = -1*np.arange(-90,90+dpp,dpp)
m = Basemap(projection='ortho', lon_0=0, lat_0=-60, resolution='l')
data = np.random.random((np.size(lats), np.size(lons)))
lons, lats = np.meshgrid(lons, lats)
x, y = m(lons, lats)
im = m.pcolormesh(x, y, data, latlon=False, cmap='RdBu')
#im = m.pcolormesh(lons, lats, data, latlon=True, cmap='RdBu')
m.colorbar(im)
plt.show()
I obtain the following plot:
The random noise should be mapped onto the entire sphere, but there is clearly an error in the upper right of the ortho map.
Does anyone else get this error with the included code?

Since basemap would require you to manually filter out unwanted data (those that are "behind the globe"), here is how to do the same with cartopy.
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
proj = ccrs.Orthographic(central_longitude=0.0, central_latitude=-60.0)
plt.figure(figsize=(3, 3))
ax = plt.axes(projection=proj)
dpp =1
lons = np.arange(-180,180+dpp,dpp)
lats = 1*np.arange(-90,90+dpp,dpp)
data = np.random.random((np.size(lats), np.size(lons)))
lons, lats = np.meshgrid(lons, lats)
im = ax.pcolormesh(lons, lats, data, cmap='RdBu', transform=ccrs.PlateCarree())
ax.coastlines(resolution='110m')
ax.gridlines()
plt.show()

A fix to Basemap was suggested in the github basemap thread here

Related

Cartopy non-zero central longitude distorted with contourf

I am trying to plot the surface temperature from a NetCDF file using Cartopy and contourf. The domain of my plot is 30S to 60N and 90.044495E to 89.95552E (so all the way around the Earth centered on 90W). Here is a section of my code:
import numpy as np
import wrf as wrf
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
cart_proj = wrf.get_cartopy(skintemp)
lats, lons = wrf.latlon_coords(skintemp)
ax = plt.axes(projection=cart_proj)
ax.coastlines('50m', linewidth=0.8)
clevels = np.linspace(230,300,8)
cmap = plt.cm.YlOrRd
contours_fill = plt.contourf(wrf.to_np(lons), wrf.to_np(lats), skintemp, cmap=cmap, levels = clevels, transform=ccrs.PlateCarree(),extend="both")
cbar = plt.colorbar(contours_fill, shrink = .65, orientation='horizontal', pad=.05)
plt.show()
skintemp, lats and lons are all 2D arrays with dimensions (454, 1483), ordered (lat,lon), and cart_proj = wrf.projection.MercatorWithLatTS.
When I show the plot, it's distorted and incorrect:
I have determined that the issue has to do with the non-zero central longitude. The problem appears to be when the longitude changes from 179.90082 to -179.85632. lons.values[0,370]=179.90082, so I changed contourf to the following:
contours_fill = plt.contourf(wrf.to_np(lons[:,0:371]), wrf.to_np(lats[:,0:371]), skintemp[:,0:371], cmap=cmap, levels = clevels, transform=ccrs.PlateCarree(),extend="both")
which produces the following correct figure:
And when I change contourf to:
contours_fill = plt.contourf(wrf.to_np(lons[:,371:-1]), wrf.to_np(lats[:,371:-1]), skintemp[:,371:-1], cmap=cmap, levels = clevels, transform=ccrs.PlateCarree(),extend="both")
I get the other part of the map:
I cannot seem to get both parts of the map to display correctly together. I tried using contourf twice in the same plot, one for each section of the map, but only the last contourf line plots. Any help would be much appreciated!

Plotting a rasterio raster on a Cartopy GeoAxes

I've seen a few other questions on this topic, but the library has changed enough that the answers to those no longer seem to apply.
Rasterio used to include an example for plotting a rasterio raster on a Cartopy GeoAxes. The example went roughly like this:
import matplotlib.pyplot as plt
import rasterio
from rasterio import plot
import cartopy
import cartopy.crs as ccrs
world = rasterio.open(r"../tests/data/world.rgb.tif")
fig = plt.figure(figsize=(20, 12))
ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine())
ax.set_global()
plot.show(world, origin='upper', transform=ccrs.PlateCarree(), interpolation=None, ax=ax)
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS)
However, this code no longer draws the raster. Instead, I get something like this:
It should look like this:
When I asked about this in the rasterio issues tracker, they told me the example was deprecated (and deleted the example). Still, I wonder if there's some way to do what I'm trying to do. Can anyone point me in the right direction?
I think you may want to read the data to a numpy.ndarray and plot it using ax.imshow, where ax is your cartopy.GeoAxes (as you have it already). I offer an example of what I mean, below.
I clipped a small chunk of Landsat surface temperature and some agricultural fields for this example. Get them on this drive link.
Note fields are in WGS 84 (epsg 4326), Landsat image is in UTM Zone 12 (epsg 32612), and I want my map in Lambert Conformal Conic. Cartopy makes this easy.
import numpy as np
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
import rasterio
import matplotlib.pyplot as plt
def cartopy_example(raster, shapefile):
with rasterio.open(raster, 'r') as src:
raster_crs = src.crs
left, bottom, right, top = src.bounds
landsat = src.read()[0, :, :]
landsat = np.ma.masked_where(landsat <= 0,
landsat,
copy=True)
landsat = (landsat - np.min(landsat)) / (np.max(landsat) - np.min(landsat))
proj = ccrs.LambertConformal(central_latitude=40,
central_longitude=-110)
fig = plt.figure(figsize=(20, 16))
ax = plt.axes(projection=proj)
ax.set_extent([-110.8, -110.4, 45.3, 45.6], crs=ccrs.PlateCarree())
shape_feature = ShapelyFeature(Reader(shapefile).geometries(),
ccrs.PlateCarree(), edgecolor='blue')
ax.add_feature(shape_feature, facecolor='none')
ax.imshow(landsat, transform=ccrs.UTM(raster_crs['zone']),
cmap='inferno',
extent=(left, right, bottom, top))
plt.savefig('surface_temp.png')
feature_source = 'fields.shp'
raster_source = 'surface_temperature_32612.tif'
cartopy_example(raster_source, feature_source)
The trick with Cartopy is to remember to use the projection keyword for your axes object, as this renders the map in a nice projection of your choice (LCC in my case). Use transform keyword to indicate what projection system your data is in, so Cartopy knows how to render it.
No need of rasterio. Get a bluemarble image, then plot it.
Here is the working code:
import cartopy
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
fig = plt.figure(figsize=(10, 5))
ax = plt.axes(projection=ccrs.InterruptedGoodeHomolosine())
# source of the image:
# https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73909/world.topo.bathy.200412.3x5400x2700.jpg
fname = "./world.topo.bathy.200412.3x5400x2700.jpg"
img_origin = 'lower'
img = plt.imread(fname)
img = img[::-1]
ax.imshow(img, origin=img_origin, transform=ccrs.PlateCarree(), extent=[-180, 180, -90, 90])
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS)
ax.set_global()
plt.show()
The output plot:

Pylab contour plot using Mollweide projection create artefacts

The purpose of the script is to do a contour plot of some data in a Mollweide projection with pylab. There is a strange behaviour of contourf. Here is the code
import numpy as np
import pylab as plt
ra = np.linspace(-np.pi, np.pi, 40)
dec= np.linspace(-np.pi/2, np.pi/2, 20)
X,Y = np.meshgrid(ra,dec)
Z = np.sin(X) * np.cos(X) * np.sin(Y) * np.cos(Y)
plt.figure()
ax = plt.subplot(111, projection = 'mollweide')
ax.contourf(X,Y,Z,100)
ax.contour(X,Y,Z,10,colors='k')
plt.show()
Some of the points seem to be wrongly drawn (See Figure below).
The same code used without projection outputs a perfectly normal map:
You may have noticed that the contour lines work perfectly in both images. The artefacts seem to be always at the same place.
Is there a way to correct this artefacts generation ?
It seems that there is some underlying issue due to the fact that the Mollweide projection has singularities for latitudes of +/- 90°. A solution suggested by #pelson on github is to use Basemap:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
ra = np.linspace(-np.pi, np.pi, 40)
dec= np.linspace(-np.pi/2, np.pi/2, 20)
X,Y = np.meshgrid(ra,dec)
Z = np.sin(X) * np.cos(X) * np.sin(Y) * np.cos(Y)
RAD = 180/np.pi
m = Basemap(projection='moll',lon_0=0,resolution='c')
m.contour(X*RAD, Y*RAD, Z, 10, colors='k',latlon=True)
m.contourf(X*RAD, Y*RAD, Z, 100, cmap=plt.cm.jet,latlon=True)
plt.show()
This code works as proven below:

viewing a polygon read from shapefile with matplotlib

I am trying to view a basic polygon read from a Shapefile using matplotlib and pyshp
But all my efforts yield just an empty axes with no polygon. Here are few of my tries, using the dataset showing the borders of Belgium:
import shapefile as sf
r = sf.Reader("BEL_adm/BEL_adm0")
p=r.shapes()
b=p[0]
points = b.points
import matplotlib.pyplot as plt
from matplotlib.path import Path
imporst matplotlib.patches as patches
verts = points
verts = []
for x,y in points:
verts.append(tuple([x,y]))
codes = ['']*len(verts)
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
for i in range(1,len(verts)):
codes[i]=Path.LINETO
path = Path(verts, codes)
fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch)
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()
Another try with patches also yields an empty frame:
fig = plt.figure(figsize=(11.7,8.3))
ax = plt.subplot(111)
x,y=zip(*b.points)
import matplotlib.patches as patches
import matplotlib.pyplot as plt
bol=patches.Polygon(b.points,True, transform=ax.transAxes)
ax.add_patch(bol)
ax.set_ylim(0,60)
ax.set_xlim(0,200)
plt.show()
Would be happy to see what I am missing.
Thanks, Oz
instead of calling set_xlim(), set_ylim() to set the range of axis, you can use ax.autoscale().
For your Polygon version, you don't need to set transform argument to ax.transAxes, just call:
bol=patches.Polygon(b.points,True)

heatmap using scatter dataset python matplotlib

I am writing a script to make a heatmap for scatter data on two dimensionS. The following is a toy example of what I am trying to do:
import numpy as np
from matplotlib.pyplot import*
x = [1,2,3,4,5]
y = [1,2,3,4,5]
heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
imshow(heatmap, extent = extent)
I should expect a the 'warmest' areas to be along y=x but instead they show up along y=-x+5 i.e the heatmap reads one list in the reverse direction. I am not sure why this is happening. Any suggestions?
Thanks
Try the imshow parameter origin=lower. By default it sets the (0,0) element of the array in the upper left corner.
For example:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,5]
y = [1,2,3,4,5,5]
heatmap, xedges, yedges = np.histogram2d(x, y, bins=10)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.imshow(heatmap, extent = extent)
ax1.set_title("imshow Default");
ax2 = fig.add_subplot(212)
ax2.imshow(heatmap, extent = extent,origin='lower')
ax2.set_title("imshow origin='lower'");
fig.savefig('heatmap.png')
Produces:
Too keep the look of the heatmap consistent with what you see in the scatter, actually use:
ax2.imshow(heatmap.T, extent = extent,origin='lower')