Axis labels for LambertConformal in cartopy at wrong location - python

I want to plot some data in a LambertConformal projection and add labels to the axes. See the example code below. However, now the x-labels show up twice, and both times in the middle of the plot, instead of at its bottom. When instead I set gl.xlabels_bottom = False and gl.xlabels_top = True, no x-labels are plotted at all. With the y-labels, I do not get this problem; they are just nicely plotted either along the left or right boundary of the plot.
How can I get the x-labels at the right location (at the bottom of the figure)?
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
bounds_lon = [-45,-25]
bounds_lat = [55,65]
lon = np.arange(bounds_lon[0],bounds_lon[1]+0.1,0.1)
lat = np.arange(bounds_lat[0],bounds_lat[1]+0.1,0.1)
Lon, Lat = np.meshgrid(lon,lat)
data = np.ones(np.shape(Lon))
data_crs = ccrs.PlateCarree()
projection = ccrs.LambertConformal(central_longitude=np.mean(bounds_lon),central_latitude=np.mean(bounds_lat),cutoff=bounds_lat[0])
plt.figure(figsize=(4,4))
ax = plt.axes(projection=projection)
ax.coastlines()
ax.contourf(Lon, Lat, data, transform=data_crs)
gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.xlabels_bottom = True

Manual repositioning of tick-labels are needed. To do that successfully, requires some other adjustments of the plot settings. Here is the code you can try.
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
bounds_lon = [-45,-25]
bounds_lat = [55,65]
# make-up data to plot on the map
inc = 0.5
lon = np.arange(bounds_lon[0],bounds_lon[1]+inc, inc)
lat = np.arange(bounds_lat[0],bounds_lat[1]+inc, inc)
Lon, Lat = np.meshgrid(lon,lat)
#data = np.ones(np.shape(Lon)) # original `boring` data
data = np.sin(Lon)+np.cos(Lat) # better data to use instead
data_crs = ccrs.PlateCarree()
projection = ccrs.LambertConformal(central_longitude=np.mean(bounds_lon), \
central_latitude=np.mean(bounds_lat), \
#cutoff=bounds_lat[0]
)
# Note: `cutoff` causes horizontal cut at lower edge
# init plot figure
plt.figure(figsize=(15,9))
ax = plt.axes(projection=projection)
ax.coastlines(lw=0.2)
ax.contourf(Lon, Lat, data, transform=data_crs, alpha=0.5)
# set gridlines specs
gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.top_labels=True
gl.bottom_labels=True
gl.left_labels=True
gl.right_labels=True
plt.draw() #enable access to lables' positions
xs_ys = ax.get_extent() #(x0,x1, y0,y1)
#dx = xs_ys[1]-xs_ys[0]
dy = xs_ys[3]-xs_ys[2]
# The extent of `ax` must be adjusted
# Extents' below and above are increased
new_ext = [xs_ys[0], xs_ys[1], xs_ys[2]-dy/15., xs_ys[3]+dy/12.]
ax.set_extent(new_ext, crs=projection)
# find locations of the labels and reposition them as needed
xs, ys = [], []
for ix,ea in enumerate(gl.label_artists):
xy = ea[2].get_position()
xs.append(xy[0])
ys.append(xy[1])
# Targeted labels to manipulate has "W" in them
if "W" in ea[2].get_text():
x_y = ea[2].get_position()
# to check which are above/below mid latitude of the plot
# use 60 (valid only this special case)
if x_y[1]<60:
# labels at lower latitudes
curpos = ea[2].get_position()
newpos = (curpos[0], 54.7) # <- from inspection: 54.7
ea[2].set_position(newpos)
else:
curpos = ea[2].get_position()
newpos = (curpos[0], 65.3) # <- from inspection: 65.3
ea[2].set_position(newpos)
plt.show()
Edit1
If you want to move all the lat/long labels to the outside edges, try this code. It is much more concise than the above.
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
bounds_lon = [-45,-25]
bounds_lat = [55,65]
inc = 0.5
lon = np.arange(bounds_lon[0],bounds_lon[1]+inc, inc)
lat = np.arange(bounds_lat[0],bounds_lat[1]+inc, inc)
Lon, Lat = np.meshgrid(lon,lat)
#data = np.ones(np.shape(Lon)) # boring data
data = np.sin(Lon)+np.cos(Lat) # more interesting
data_crs = ccrs.PlateCarree()
projection = ccrs.LambertConformal(central_longitude=np.mean(bounds_lon), \
central_latitude=np.mean(bounds_lat), \
cutoff=bounds_lat[0]
)
# init plot
plt.figure(figsize=(15,9))
ax = plt.axes(projection=projection)
ax.coastlines(lw=0.2)
ax.contourf(Lon, Lat, data, transform=data_crs, alpha=0.3)
gl = ax.gridlines(draw_labels=True, x_inline=False, y_inline=False,
color='k', linestyle='dashed', linewidth=0.5)
gl.top_labels=True
gl.bottom_labels=True
gl.left_labels=True
gl.right_labels=True
plt.show()
If you want to get bottom edge as a straight line, you can achieve that by dropping the option cutoff=bounds_lat[0] from this line of code:-
projection = ccrs.LambertConformal(central_longitude=np.mean(bounds_lon), \
central_latitude=np.mean(bounds_lat), \
cutoff=bounds_lat[0]
)
so that it becomes
projection = ccrs.LambertConformal(central_longitude=np.mean(bounds_lon),
central_latitude=np.mean(bounds_lat))
and you will get the plot like this:-

Related

How to plot the map correctly over the SST data in cartopy?

I am trying to plot L2 Sea Surface Temperature data and I want to plot it over the globe in a geostationary projection. I tried the following code:
import h5py
import sys
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
# First get data from HDF5 file with h5py:
fn = '/home/swadhin/project/insat/data/3RIMG_30MAR2018_0014_L2B_SST_V01R00.h5'
with h5py.File(fn) as f:
print(list(f.keys()))
image = 'SST'
img_arr = f[image][0,:,:]
# get _FillValue for data masking
img_arr_fill = f[image].attrs['_FillValue'][0]
# retrieve extent of plot from file attributes:
left_lon = f.attrs['left_longitude'][0]
right_lon = f.attrs['right_longitude'][0]
lower_lat = f.attrs['lower_latitude'][0]
upper_lat = f.attrs['upper_latitude'][0]
sat_long = f.attrs['Nominal_Central_Point_Coordinates(degrees)_Latitude_Longitude'][1]
sat_hght = f.attrs['Nominal_Altitude(km)'][0] * 1000.0 # (for meters)
print('Done reading HDF5 file')
## Use np.ma.masked_equal with integer values to
## mask '_FillValue' data in corners:
img_arr_m = np.ma.masked_equal(img_arr, img_arr_fill)
print(img_arr_fill)
print(np.max(img_arr_m))
print(np.min(img_arr_m))
#print(np.shape(img_arr_m))
# # Create Geostationary plot with cartopy and matplotlib
map_proj = ccrs.Geostationary(central_longitude=sat_long,satellite_height=sat_hght)
ax = plt.axes(projection=map_proj)
ax.coastlines(color='black',linewidth = 0.5)
#ax.add_feature(cfeature.BORDERS, edgecolor='white', linewidth=0.25)
#ax.add_feature(cfeature.STATES,edgecolor = 'red',linewidth = 0.5)
ax.gridlines(color='black', alpha=0.5, linestyle='--', linewidth=0.75, draw_labels=True)
#ax.add_geometries(ind_shapes,crs = map_proj, edgecolor = 'black', alpha = 0.5)
map_extend_geos = ax.get_extent(crs=map_proj)
plt.imshow(img_arr_m, interpolation='none',origin='upper',extent=map_extend_geos, cmap = 'jet')
plt.colorbar()
#plt.clim(-10,5)
plt.savefig('/home/swadhin/project/insat/data/l2_sst.png',format = 'png', dpi=1000)
The output I got is not very accurate. There are some SST values over some of the land areas which should not be the case.
I am adding the data here for people who wanna give it a try.
https://drive.google.com/file/d/126oW36JXua-zz3XMUcyZxwPj8UISDgUM/view?usp=sharing
I have checked your HDF5 file, and there are Longitude and Latitude variables in the file. So I think these WGS84 coordinates should be used.
First, the imshow method needs the image boundary information that cannot be obtained.
I also tried the pcolormesh method, but this method can not accept lon/lat array with NaN value.
In conclusion, the contourf seems to be the best choice, but this method still has the disadvantage that it is time-consuming to run.
import h5py
import sys
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
fn ='3RIMG_30MAR2018_0014_L2B_SST_V01R00.h5'
with h5py.File(fn) as f:
print(list(f.keys()))
image = 'SST'
img_arr = f[image][0,:,:]
lon = f['Longitude'][:]*0.01
lat = f['Latitude'][:]*0.01
# # get _FillValue for data masking
img_arr_fill = f[image].attrs['_FillValue'][0]
# # retrieve extent of plot from file attributes:
left_lon = f.attrs['left_longitude'][0]
right_lon = f.attrs['right_longitude'][0]
lower_lat = f.attrs['lower_latitude'][0]
upper_lat = f.attrs['upper_latitude'][0]
sat_long = f.attrs['Nominal_Central_Point_Coordinates(degrees)_Latitude_Longitude'][1]
sat_hght = f.attrs['Nominal_Altitude(km)'][0] * 1000.0 # (for meters)
print('Done reading HDF5 file')
## Use np.ma.masked_equal with integer values to
## mask '_FillValue' data in corners:
img_arr_m = np.ma.masked_equal(img_arr, img_arr_fill)
print(img_arr_fill)
print(np.max(img_arr_m))
print(np.min(img_arr_m))
lon_m = np.ma.masked_equal(lon, 327.67)
lat_m = np.ma.masked_equal(lat, 327.67)
# # Create Geostationary plot with cartopy and matplotlib
map_proj = ccrs.Geostationary(central_longitude=sat_long,satellite_height=sat_hght)
# or map_proj = ccrs.PlateCarree()
ax = plt.axes(projection=map_proj)
ax.set_global()
ax.coastlines(color='black',linewidth = 0.5)
ax.add_feature(cfeature.BORDERS, edgecolor='white', linewidth=0.25)
ax.add_feature(cfeature.STATES,edgecolor = 'red',linewidth = 0.5)
ax.gridlines(color='black', alpha=0.5, linestyle='--', linewidth=0.75, draw_labels=True)
cb = ax.contourf(lon_m,lat_m,img_arr_m, cmap = 'jet',transform = ccrs.PlateCarree())
plt.colorbar(cb)
plt.savefig('l2_sst1.png',format = 'png', dpi=300)
Here is the output figure.
or using a lon-lat projection.

Removing Edge colors in Cartopy heatmap

I am attempting to plot a heatmap showing the density of lightning using python's cartopy and matplotlib libraries.
I have roughly followed the code here Cartopy Heatmap over OpenStreetMap Background . However, my plot shown below contains solid lines around each transparent bin, which is my problem. The other plot is the same code with random numbers. An ideal solution would be to not display the lines at all, or for the lines to match the bin's face color with the correct transparency. I've done a fair amount of trial and error to remove them in addition to reading some matplotlib documentation. According to the 2d-histogram docs , I should be plotting a QuadMesh object. You should be able to set the linewidth to 0, or have the edgecolor set to none in the QuadMesh. In my code below, I tried doing that yet the lines still persist. I've also tried the pcolormesh as well with the same result.
Here is my code.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import cartopy.feature as cfeature
import cartopy.io.img_tiles as cimgt
import numpy as np
import random
#xsize and ysize are integers and lons, lats are 1d numpy arrays of longitude and latitude.
def testDensity(xsize, ysize, lons, lats):
#Some code below follows example
#https://stackoverflow.com/questions/50611018/cartopy-heatmap-over-openstreetmap-background
request = cimgt.OSM()
fig, ax = plt.subplots(figsize=(xsize,ysize),subplot_kw=dict(projection=request.crs), dpi=200)
extent = [-126,-118,41,44]
ax.set_extent(extent)
ax.add_image(request,8)
xynps = ax.projection.transform_points(ccrs.Geodetic(), lons, lats)#
print(xynps, type(xynps))
#Create 2-d histogram
histogram = ax.hist2d( xynps[:,0] , xynps[:,1] ,cmap='jet', bins=100, zorder=1,alpha=0.5,edgecolors="none",linewidth=0 )
print(histogram[3], dir(histogram[3]) )
histogram[3].set_linewidth(0.0)
histogram[3].set_edgecolor("none")
#histogram:(frequency, xedges, yedges, image QuadMesh)
#ax.pcolormesh(histogram[1], histogram[2], histogram[0], cmap = 'jet', alpha=0.5,edgecolors="none")
cbar = plt.colorbar(mappable=histogram[3], ax=ax , shrink=0.5, format='%.1f1' )
cbar.solids.set_rasterized("True")#Removes lines from colorbar
cbar.solids.set_edgecolor("face")
plt.savefig("densityTest.png", bbox_inches="tight")
#Generate random dataset
for i in range(0,800):
lon = random.randrange(41,44) + random.random()
lat = random.randrange(-126,-118) + random.random()
lons.append(lon)
lats.append(lat)
lons = np.array(lons)
lats = np.array(lats)
testDensity(9,34, lons, lats)
I can't reproduce the problematic results you showed us because of errors in your code. But once I correct the errors in the code and run. I get a good result as shown below.
The modified code:
def testDensity(xsize, ysize, lons, lats):
# Some code below follows example
# https://stackoverflow.com/questions/50611018/cartopy-heatmap-over-openstreetmap-background (That's my another answer)
request = cimgt.OSM()
fig, ax = plt.subplots(figsize=(xsize,ysize),subplot_kw=dict(projection=request.crs), dpi=200)
extent = [-126, -118, 41, 44]
ax.set_extent(extent)
ax.add_image(request, 8)
xynps = ax.projection.transform_points(ccrs.Geodetic(), lons, lats)
#Create 2-d histogram
# histogram = ax.hist2d(xynps[:,0],xynps[:,1],cmap='jet',bins=100,zorder=1,alpha=0.5,edgecolors="none",linewidth=0)
#This produces the same result, but shorter.
histogram = ax.hist2d( xynps[:,0], xynps[:,1], cmap='jet', bins=100, zorder=1, alpha=0.5)
# (Why use these code?)
#histogram[3].set_linewidth(0.0)
#histogram[3].set_edgecolor("none")
#ax.pcolormesh(histogram[1], histogram[2], histogram[0], cmap = 'jet', alpha=0.5,edgecolors="none")
# cbar = plt.colorbar(mappable=histogram[3], ax=ax , shrink=0.5, format='%.1f' )
# cbar.solids.set_rasterized("True")#Removes lines from colorbar
# cbar.solids.set_edgecolor("face")
# ... when this produces good result.
cbar = plt.colorbar(histogram[3], ax=ax, pad=0.03, aspect=28, shrink=0.26, format='%.1f') # h[3]: image
plt.savefig("densityTest.png", bbox_inches="tight")
plt.show()
#Generate random dataset
lons = []
lats = []
for i in range(0,800):
lat = random.randrange(41,44) + random.random()
lon = random.randrange(-126,-118) + random.random()
lons.append(lon)
lats.append(lat)
lons = np.array(lons)
lats = np.array(lats)
#testDensity(9,34, lons, lats)
testDensity(10,16, lons, lats)
The output plot:

Reproducing extent of cartopy plots with orthographic projection

I am generating set of different maps and I would like them to all have the same axis limits. However, I am having a hard time figuring out how to set the extent.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
lon = -90
lat = 90
proj = ccrs.Orthographic
projection = proj(lon, lat)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection = projection)
transform = ccrs.Geodetic()
lat0 = 50
lon0 = 50
for x in range(-5,6):
plt.plot(lon0 + x, lat0, 'bo', transform = transform)
plt.plot(lon0, lat0 + x, 'bo', transform = transform)
I want to be able to extract the extent of the "map" and then apply it to other maps that will autoscale differently. However, even when I try to extract the extent and reapply it to the same figure, it fails.
a = ax.get_extent(crs = proj())
#a = (2769836.95350539, 3487499.8040009444, 4467034.2547478145, 5254224.255689873)
ax.set_extent(a, crs = proj())
Kind of obvious once I realized it, but the lon and lat of projection need to be specified in the extent description.
a = ax.get_extent(crs = proj(lon, lat))
ax.set_extent(a, crs = proj(lon, lat))

Contour plot on a world map centered at the Pacific

I'm trying to plot some data on the world map, which can be centered either near the Atlantic (i.e. 180°W–180°E) or at the Pacific (i.e. 0°–360°). Here's the program (with fictitious data):
import argparse
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
parser = argparse.ArgumentParser()
parser.add_argument('--center', choices=['atlantic', 'pacific'], default='atlantic')
parser.add_argument('--outfile', default='plot.png')
args = parser.parse_args()
lat = np.linspace(-89.95, 89.95, 1800)
if args.center == 'atlantic':
lon = np.linspace(-179.95, 179.95, 3600)
clon = 0
else:
lon = np.linspace(0.05, 359.95, 3600)
clon = 180
x, y = np.meshgrid(lon, lat)
z = np.sin(x / 180 * np.pi) * np.sin(y / 180 * np.pi)
fig = plt.figure(figsize=(21, 7))
crs = ccrs.PlateCarree(central_longitude=clon)
ax = plt.axes(projection=crs)
ax.coastlines(resolution='110m', color='white', linewidth=2)
gl = ax.gridlines(crs=crs, draw_labels=True, linewidth=1, color='black', linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 16, 'color': 'black'}
gl.ylabel_style = {'size': 16, 'color': 'black'}
plt.contourf(x, y, z, cmap='RdYlBu_r')
cb = plt.colorbar(ax=ax, orientation='vertical', pad=0.02, aspect=16, shrink=0.8)
cb.ax.tick_params(labelsize=16)
fig.savefig(args.outfile, bbox_inches='tight', pad_inches=0.1)
However, when I switch from --center=atlantic to --center=pacific, only the coastlines move, while the X-axis and the data do not, resulting in an inconsistent plot. (With my fictitious data, North America should be in blue and Asia should be in red.)
--center=atlantic:
--center=pacific:
How can I make a correct plot that's centered at the Pacific?
It looks like I need the following changes:
Have a vanilla PlateCarree object (in addition to the existing one with central_longitude set) and use it in all cases except the call to plt.axes. (I don't understand why, but I find that it works.)
Add a call to ax.set_extent, also with the vanilla PlateCarree object.
Use transform in plt.contourf, also with the vanilla PlateCarree object.
Here's the diff from the original code:
## -23,0 +24 ##
+crs0 = ccrs.PlateCarree()
## -25,0 +27 ##
+ax.set_extent([lon[0], lon[-1], lat[0], lat[-1]], crs=crs0)
## -28 +30 ##
-gl = ax.gridlines(crs=crs, draw_labels=True, linewidth=1, color='black', linestyle='--')
+gl = ax.gridlines(crs=crs0, draw_labels=True, linewidth=1, color='black', linestyle='--')
## -34 +36 ##
-plt.contourf(x, y, z, cmap='RdYlBu_r')
+plt.contourf(x, y, z, cmap='RdYlBu_r', transform=crs0)
This produces 180°W and 180°E overwritten on top of each other. As a quick fix, I did this:
import matplotlib.ticker as mticker
# Fix LONGITUDE_FORMATTER so that either +180 or -180 returns just '180°',
# instead of '180°E' or '180°W'.
LONGITUDE_FORMATTER_NEW = mticker.FuncFormatter(
lambda v, pos: '180\u00B0' if abs(v) == 180 else LONGITUDE_FORMATTER.func(v, pos)
)
so that the identical strings 180° are overwritten at the same position on top of each other, minimizing the visual effect of the problem.
(LONGITUDE_FORMATTER doesn't handle anything beyond [−180, +180] properly, either, but I choose not to go into that here.)
Here's the result:
--center=atlantic:
--center=pacific:

Aligning data (contourf) on Basemap

I've started working with Basemap, which seems potentially very useful.
If I plot some global data on a latitude/longitude grid as filled contours, it works great: Iff I leave the lat_0 and lon_0 as zero. Once I change the center location, the map moves but the data doesn't. I would be grateful for advice.
I've created a simple version of the code I'm using, with some simple sample data that illustrates the problem. The values should be (are) large at the equator but small at the poles. If you run the code with lat_0 and lon_0 = 0, it works fine. But if you change the center location to a different coordinate, the same pattern/data is presented even though the map has moved.
from mpl_toolkits.basemap import Basemap, cm
import matplotlib.pyplot as plt
import numpy as np
# create data
lat = np.linspace(-90,90,num=180)
lon = np.linspace(-180,180,num=361)
h2o_north = np.linspace(1,65,num=90)
h2o_south = np.flipud(h2o_north)
h2o = np.append(h2o_north,h2o_south)
data = np.transpose(np.tile(h2o,(len(lon),1)))
# create figure and axes instances
fig = plt.figure(figsize=(10,10))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
# create map
m = Basemap(projection='ortho',lon_0=-50,lat_0=50,resolution='l')
# draw coastlines and country boundaries
m.drawcoastlines()
m.drawcountries()
# draw parallels
parallels = np.arange(-90.,90,10.)
m.drawparallels(parallels)
# draw meridians
meridians = np.arange(180.,360.,10.)
m.drawmeridians(meridians)
ny = data.shape[0]
nx = data.shape[1]
lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid
x, y = m(lons, lats) # compute map projection coordinates
# draw filled contours.
clevs = np.linspace(0,70,num=281)
cs = m.contourf(x,y,data,clevs,cmap=plt.cm.jet)
# colorbar
cbar = m.colorbar(cs,location='bottom',pad="5%",ticks=np.linspace(0,70,15))
cbar.set_label('Scale of the data')
plt.title('Some global data', fontsize=14)
Use np.meshgrid() to create the meshgrid of lon-lat, then, convert it to projection coordinates, and the data are ready to generate contours and plot.
Here is the working code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# data for z (2D array)
h2o_north = np.linspace(1, 65, num=90)
h2o_south = np.flipud(h2o_north)
h2o = np.append(h2o_north, h2o_south)
data = np.transpose(np.tile(h2o, (len(h2o_north), 1)))
# create figure and axes instances
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot()
# create basemap instance
m = Basemap(projection='ortho', lon_0=-50, lat_0=50, resolution='c', ax=ax)
# create meshgrid covering the whole globe with ...
# conforming dimensions of the `data`
lat = np.linspace(-90, 90, data.shape[0])
lon = np.linspace(-180, 180, data.shape[1])
xs, ys = np.meshgrid(lon, lat) # basic mesh in lon, lat (degrees)
x, y = m(xs, ys) # convert (lon,lat) to map (x,y)
# draw filled contours
clevs = np.linspace(0, np.max(data), 60)
cs = m.contourf(x, y, data, clevs, cmap=plt.cm.jet)
m.drawcoastlines()
m.drawcountries()
m.drawmeridians(range(-180, 180, 30))
m.drawparallels(range(-90, 90, 30))
# draw colorbar
cbar = m.colorbar(cs, location='bottom', pad="5%", ticks=np.linspace(0, np.max(data), 5))
cbar.set_label('Scale of the data')
plt.show()
The resulting plot:

Categories

Resources