def test_inverted_poly_simple_hole(self): proj = ccrs.NorthPolarStereo() poly = sgeom.Polygon([(0, 0), (-90, 0), (-180, 0), (-270, 0)], [[(0, -30), (90, -30), (180, -30), (270, -30)]]) multi_polygon = proj.project_geometry(poly) # Check the structure self.assertEqual(len(multi_polygon), 1) self.assertEqual(len(multi_polygon[0].interiors), 1) # Check the rough shape polygon = multi_polygon[0] self._assert_bounds(polygon.bounds, -2.4e7, -2.4e7, 2.4e7, 2.4e7, 1e6) self._assert_bounds(polygon.interiors[0].bounds, -1.2e7, -1.2e7, 1.2e7, 1.2e7, 1e6)
def test_quiver_regrid(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = np.cos(np.deg2rad(y2d)) v = np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] plt.figure(figsize=(6, 3)) ax = plt.axes(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.quiver(x, y, u, v, mag, transform=ccrs.PlateCarree(), regrid_shape=30)
def make_plot(srcCoord, srcData, dstCoord, dstData, month=1): it = month-1 fig = plt.figure( figsize=(20,8) ) gs = gridspec.GridSpec(2, 2, height_ratios=(30,1)) ax1 = fig.add_subplot(gs[0], projection=ccrs.NorthPolarStereo()) ax1.set_extent([-180,180,40,90], ccrs.PlateCarree()) pcm = ax1.pcolormesh(srcCoord[0], srcCoord[1], srcData, cmap = 'gist_ncar', transform=ccrs.PlateCarree(), vmin = 0, vmax = 6) ax1.add_feature(cfeature.COASTLINE) ax1.set_title('PIOMAS Mask - Original') ax2 = fig.add_subplot(gs[1], projection=ccrs.NorthPolarStereo()) ax2.set_extent([-180,180,40,90], ccrs.PlateCarree()) ax2.pcolormesh(dstCoord[0], dstCoord[1], dstData, cmap = 'gist_ncar', transform=ccrs.PlateCarree(), vmin = 0, vmax = 6) ax2.add_feature(cfeature.COASTLINE) ax2.set_title('Regridded') plt.show()
def multi_polar_axis(ncols, nrows, Nplots=None, sizefcter=1, extent=None, central_longitude=-45): if not Nplots: Nplots = ncols * nrows # Create a grid of plots f, (axes) = plt.subplots( ncols=ncols, nrows=nrows, subplot_kw={ 'projection': ccrs.NorthPolarStereo(central_longitude=central_longitude) }) f.set_size_inches(ncols * 1.5 * sizefcter, nrows * 2 * sizefcter) axes = axes.reshape(-1) for (i, ax) in enumerate(axes): axes[i].coastlines(linewidth=0.2, color='black', resolution='50m') axes[i].gridlines(crs=ccrs.PlateCarree(), linestyle='--', linewidth=0.20, color='grey') #ax.set_extent([0, 359.9, 57, 90], crs=ccrs.PlateCarree()) # Full NSIDC extent if not extent: axes[i].set_extent( [-3850000 * 0.9, 3725000 * 0.8, -5325000 * 0.7, 5850000 * 0.9], crs=ccrs.NorthPolarStereo(central_longitude=central_longitude)) else: # Set Regional extent axes[i].set_extent( extent, crs=ccrs.NorthPolarStereo(central_longitude=central_longitude)) if i >= Nplots - 1: f.delaxes(axes[i]) return (f, axes)
def set_up_subplot(fig,subplot=111): crs_np = ccrs.NorthPolarStereo(central_longitude=-45) ax = fig.add_subplot(subplot,projection=crs_np) xll, yll = crs_np.transform_point(279.26,33.92, ccrs.Geodetic()) xur, yur = crs_np.transform_point(102.34,31.37, ccrs.Geodetic()) ax.set_extent([xll,xur,yll,yur],crs=crs_np) ax.add_feature(cfeature.OCEAN,facecolor='c', zorder=1) ax.add_feature(cfeature.LAND,facecolor='0.3', zorder=3) ax.add_feature(cfeature.LAKES,facecolor='c',linestyle='-', edgecolor='k',zorder=3) ax.coastlines(resolution='110m',linewidth=1,color='k',zorder=3) return ax
def test_fetch_img_reprojected_twoparts(self): source = ogc.WMTSRasterSource(self.URI, self.layer_name) extent = [-10, 12, 48, 50] images = source.fetch_raster(ccrs.NorthPolarStereo(), extent, (30, 30)) # Check for 2 results in this case. assert len(images) == 2 im1, im2 = images # Check image arrays is as expected (more or less). assert np.array(im1.image).shape == (42, 42, 4) assert np.array(im2.image).shape == (42, 42, 4) # When reprojected, extent is exactly what you asked for. assert im1.extent == extent assert im2.extent == extent
def test_streamplot(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = np.cos(np.deg2rad(y2d)) v = np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] plt.figure(figsize=(6, 3)) ax = plt.axes(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.streamplot(x, y, u, v, transform=ccrs.PlateCarree(), density=(1.5, 2), color=mag, linewidth=2*mag)
def plot(lat, lon, Z, date, time, intfactor, maxtec, aacgm, plottype, extent): tecmap = plt.figure(figsize=(11, 8)) if plottype == 'Northern Hemisphere': map_proj = ccrs.NorthPolarStereo() elif plottype == 'Southern Hemisphere': map_proj = ccrs.SouthPolarStereo() elif plottype == 'Global': map_proj = ccrs.PlateCarree() if aacgm: ax = tecmap.add_subplot(projection='aacgmv2', map_projection=map_proj) ax.overaly_coast_lakes(coords="aacgmv2", plot_date=date) if map_proj == ccrs.PlateCarree(): mesh = ax.pcolor(lon, lat, Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree()) else: mesh = ax.scatter(lon, lat, c=Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree()) else: #usepcolormesh in ax = plt.axes(projection=map_proj) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.LAKES) mesh = ax.pcolormesh(lon, lat, Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree()) ax.set_extent(extent, ccrs.PlateCarree()) clrbar = plt.colorbar(mesh, shrink=0.5) clrbar.set_label('Total Electron Content (TECU)') ax.gridlines(linewidth=0.5) plt.title('Total Electron Content for ' + str(date.month) + '/' + str(date.day) + '/' + str(date.year) + ' at ' + str(time.hour) + ':' + ('%02d' % time.minute) + ' UT') st.pyplot(tecmap)
def test_barbs_regrid(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = 40 * np.cos(np.deg2rad(y2d)) v = 40 * np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] fig = plt.figure(figsize=(6, 3)) ax = fig.add_subplot(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.barbs(x, y, u, v, mag, transform=ccrs.PlateCarree(), length=4, linewidth=.4, regrid_shape=20) return fig
def lookup_projection(projection_code): """Get a Cartopy projection based on a short abbreviation.""" import cartopy.crs as ccrs projections = { 'lcc': ccrs.LambertConformal(central_latitude=40, central_longitude=-100, standard_parallels=[30, 60]), 'ps': ccrs.NorthPolarStereo(central_longitude=-100), 'mer': ccrs.Mercator() } return projections[projection_code]
def test_inverted_poly_clipped_hole(self): proj = ccrs.NorthPolarStereo() poly = sgeom.Polygon([(0, 0), (-90, 0), (-180, 0), (-270, 0)], [[(-135, -60), (-45, -60), (45, -60), (135, -60)]]) multi_polygon = proj.project_geometry(poly) # Check the structure assert len(multi_polygon) == 1 assert len(multi_polygon[0].interiors) == 1 # Check the rough shape polygon = multi_polygon[0] self._assert_bounds(polygon.bounds, -5.0e7, -5.0e7, 5.0e7, 5.0e7, 1e6) self._assert_bounds(polygon.interiors[0].bounds, -1.2e7, -1.2e7, 1.2e7, 1.2e7, 1e6) assert abs(polygon.area - 7.30e15) < 1e13
def test_inverted_poly_removed_hole(self): proj = ccrs.NorthPolarStereo(globe=ccrs.Globe(ellipse='WGS84')) poly = sgeom.Polygon([(0, 0), (-90, 0), (-180, 0), (-270, 0)], [[(-135, -75), (-45, -75), (45, -75), (135, -75)]]) multi_polygon = proj.project_geometry(poly) # Check the structure self.assertEqual(len(multi_polygon), 1) self.assertEqual(len(multi_polygon[0].interiors), 1) # Check the rough shape polygon = multi_polygon[0] self._assert_bounds(polygon.bounds, -5.0e7, -5.0e7, 5.0e7, 5.0e7, 1e6) self._assert_bounds(polygon.interiors[0].bounds, -1.2e7, -1.2e7, 1.2e7, 1.2e7, 1e6) self.assertAlmostEqual(polygon.area, 7.34e15, delta=1e13)
def make_graph(Dataset, Name, filename, central): lats = nc.variables['lat'][:] lons = nc.variables['lon'][:] avg, lons = add_cyclic_point(Dataset, coord=lons) fig = figure() ax = axes(projection=ccrs.NorthPolarStereo(central_longitude=central)) cs = contourf(lons, lats, avg, cmap='nipy_spectral', alpha=0.8, transform=ccrs.PlateCarree()) ax.coastlines() colorbar(orientation='horizontal') plot() savefig("NorthPolarStereo/" + str(Name) + ".png")
def test_inverted_poly_clipped_hole(self): proj = ccrs.NorthPolarStereo() poly = Polygon([(0, 0), (90, 0), (180, 0), (270, 0)], [[(135, -60), (45, -60), (-45, -60), (-135, -60)]]) multi_polygon = proj.project_geometry(poly) # Check the structure self.assertEqual(len(multi_polygon), 1) self.assertEqual(len(multi_polygon[0].interiors), 1) # Check the rough shape polygon = multi_polygon[0] self._assert_bounds(polygon.bounds, -5.0e7, -5.0e7, 5.0e7, 5.0e7, 1e6) self._assert_bounds(polygon.interiors[0].bounds, -1.2e7, -1.2e7, 1.2e7, 1.2e7, 1e6) self.assertAlmostEqual(polygon.area, 7.30e15, delta=1e13)
def test_quiver_regrid_with_extent(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = np.cos(np.deg2rad(y2d)) v = np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] target_extent = [-3e6, 2e6, -6e6, -2.5e6] fig = plt.figure(figsize=(6, 3)) ax = fig.add_subplot(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.quiver(x, y, u, v, mag, transform=ccrs.PlateCarree(), regrid_shape=10, target_extent=target_extent) return fig
def test_barbs_regrid_with_extent(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = 40 * np.cos(np.deg2rad(y2d)) v = 40 * np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] target_extent = [-3e6, 2e6, -6e6, -2.5e6] plt.figure(figsize=(6, 3)) ax = plt.axes(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.barbs(x, y, u, v, mag, transform=ccrs.PlateCarree(), length=4, linewidth=.25, regrid_shape=10, target_extent=target_extent)
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(approx=True), ccrs.TransverseMercator(approx=True), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(emphasis='land'), ccrs.EckertI(), ccrs.EckertII(), ccrs.EckertIII(), ccrs.EckertIV(), ccrs.EckertV(), ccrs.EckertVI(), ] rows = np.ceil(len(projections) / 5).astype(int) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines(resolution="110m") plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def test_multiple_projections(): projections = [ ccrs.PlateCarree(), ccrs.Robinson(), ccrs.RotatedPole(pole_latitude=45, pole_longitude=180), ccrs.OSGB(), ccrs.TransverseMercator(), ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)), min_latitude=-85., max_latitude=85.), ccrs.LambertCylindrical(), ccrs.Miller(), ccrs.Gnomonic(), ccrs.Stereographic(), ccrs.NorthPolarStereo(), ccrs.SouthPolarStereo(), ccrs.Orthographic(), ccrs.Mollweide(), ccrs.InterruptedGoodeHomolosine(), ] if ccrs.PROJ4_VERSION < (5, 0, 0): # Produce the same sized image for old proj, to avoid having to replace # the image. If this figure is regenerated for both old and new proj, # then drop this condition. rows = 5 else: rows = np.ceil(len(projections) / 5) fig = plt.figure(figsize=(10, 2 * rows)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(rows, 5, i, projection=prj) ax.set_global() ax.coastlines() plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='red', transform=ccrs.PlateCarree()) plt.plot([-0.08, 132], [51.53, 43.17], color='blue', transform=ccrs.Geodetic())
def plot(reference, test, diff, metrics_dict, parameter): # Create figure, projection fig = plt.figure(figsize=[8.5, 11.0]) # Create projection print parameter.var_region if parameter.var_region.find('N') !=-1: pole = 'N' proj = ccrs.NorthPolarStereo(central_longitude=0) elif parameter.var_region.find('S') !=-1: pole = 'S' proj = ccrs.SouthPolarStereo(central_longitude=0) # First two panels min1 = metrics_dict['test']['min'] mean1 = metrics_dict['test']['mean'] max1 = metrics_dict['test']['max'] if test.count() >1: plot_panel(0, fig, proj, pole, test, parameter.contour_levels, 'viridis', (parameter.test_name,parameter.test_title,test.units),stats=(max1,mean1,min1)) min2 = metrics_dict['ref']['min'] mean2 = metrics_dict['ref']['mean'] max2 = metrics_dict['ref']['max'] if reference.count() >1: plot_panel(1, fig, proj, pole, reference, parameter.contour_levels, 'viridis', (parameter.reference_name,parameter.reference_title,reference.units),stats=(max2,mean2,min2)) # Third panel min3 = metrics_dict['diff']['min'] mean3 = metrics_dict['diff']['mean'] max3 = metrics_dict['diff']['max'] r = metrics_dict['misc']['rmse'] c = metrics_dict['misc']['corr'] if diff.count() >1: plot_panel(2, fig, proj, pole, diff, parameter.diff_levels, 'RdBu_r', (None,parameter.diff_title,None), stats=(max3,mean3,min3,r,c)) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.97, fontsize=18) # Save figure for f in parameter.output_format: f = f.lower().split('.')[-1] fnm = os.path.join(get_output_dir('7', parameter), parameter.output_file) plt.savefig(fnm + '.' + f) print('Plot saved in: ' + fnm + '.' + f)
def plot_contour(lons, lats, data, levels=[.15], colors=['purple'], lw=[1.], labels=['Variable'], outname='test.png'): # create the figure panel fig = plt.figure(figsize=(10, 10), facecolor='w') # create the map using the cartopy NorthPoleStereo # +proj=stere +a=6378273 +b=6356889.44891 +lat_0=90 +lat_ts=70 +lon_0=-45" globe = cartopy.crs.Globe(semimajor_axis=6378273, semiminor_axis=6356889.44891) ax1 = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo(central_longitude=-45, true_scale_latitude=70, globe=globe)) ax1.set_extent([15, -180, 72, 62], crs=ccrs.PlateCarree()) # add coastlines, gridlines, make sure the projection is maximised inside the plot, and fill in the land with colour ax1.coastlines( resolution='110m', zorder=3 ) # zorder=3 makes sure that no other plots overlay the coastlines ax1.gridlines() ax1.add_feature(cartopy.feature.LAND, zorder=1, facecolor=cartopy.feature.COLORS['land_alt1']) # plot sea ice field for i in range(len(levels)): cs = plt.contour(lons, lats, data[i], levels=[levels[i]], colors=colors[i], linewidths=lw[i], transform=ccrs.PlateCarree()) cs.collections[0].set_label(labels[i]) ax1.legend(loc='upper right') plt.savefig(outname, bbox_inches='tight') plt.close()
def plot_transect_map(lon_start, lat_start, lon_end, lat_end, mesh, npoints=30, view='w', stock_img=False): # plt.figure(figsize=(10,10)) lonlat = transect_get_lonlat(lon_start, lat_start, lon_end, lat_end, npoints=npoints) nodes = transect_get_nodes(lonlat, mesh) dist = transect_get_distance(lonlat) if view == 'w': ax = plt.subplot(111, projection=ccrs.Mercator(central_longitude=0)) ax.set_extent([180, -180, -80, 90], crs=ccrs.PlateCarree()) elif view == 'np': ax = plt.subplot(111, projection=ccrs.NorthPolarStereo(central_longitude=0)) ax.set_extent([180, -180, 60, 90], crs=ccrs.PlateCarree()) elif view == 'sp': ax = plt.subplot(111, projection=ccrs.SouthPolarStereo(central_longitude=0)) ax.set_extent([180, -180, -90, -50], crs=ccrs.PlateCarree()) else: raise ValueError( 'The "{}" is not recognized as valid view option.'.format(view)) ax.scatter(lonlat[:, 0], lonlat[:, 1], s=30, c='b', transform=ccrs.PlateCarree()) ax.scatter(mesh.x2[nodes], mesh.y2[nodes], s=30, c='r', transform=ccrs.PlateCarree()) if stock_img == True: ax.stock_img() ax.coastlines(resolution='50m') return ax
def plot_ToE(z, zlat, zlon, title, outname, llim, ulim, by, clabel): fig = plt.figure(figsize=(6, 6), dpi=300) # some plot parameters levs = np.arange(llim, ulim + by, by) cticks = np.arange(llim, ulim + by, by) # set up map prj = ccrs.NorthPolarStereo() ax = fig.add_axes([0.05, 0.05, 0.9, 0.90], projection=prj) # left, bottom, width, height ax.coastlines() # has to be done before data to plot added for use_as_clip_path to work llon = -180 ulon = 180 llat = 20 ulat = 90 ax.set_extent([llon, ulon, llat, ulat], ccrs.PlateCarree()) 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) ax.set_boundary(circle, transform=ax.transAxes, use_as_clip_path=True) # add data # add cyclic point to wrap around in longitude (cartopy function); outputs as np array #cyclic_z, cyclic_lon = add_cyclic_point(z, coord=z['lon']) cyclic_z, cyclic_lon = add_cyclic_point(z, coord=zlon) cplot = ax.contourf(cyclic_lon, zlat, cyclic_z, transform=ccrs.PlateCarree(), extend='both', levels=levs, cmap=cm.afmhot) plt.title(title, fontsize=18) # colorbar cbar = plt.colorbar(cplot, orientation='vertical', ticks=cticks) cbar.set_label(clabel, size=12) cbar.ax.tick_params(labelsize=12) plt.savefig(outname) plt.close()
def plot_single_lat_lon(z, zlat, zlon, title, outname, lim, by, cbarlim, cbarby, clabel, zsig=0, colorscale='BlueRed'): fig = plt.figure(figsize=(6, 6), dpi=300) # some plot parameters levs = np.arange(-lim,lim+by,by) cbarticks = np.arange(-cbarlim,cbarlim+cbarby,cbarby) cols = color_defs.custom(colorscale) # set up map prj = ccrs.NorthPolarStereo() ax = fig.add_axes([0.05, 0.05, 0.9, 0.90], projection=prj) # left, bottom, width, height ax.coastlines() # has to be done before data to plot added for use_as_clip_path to work llon=-180 ulon=180 llat=20 ulat=90 ax.set_extent([llon, ulon, llat, ulat], ccrs.PlateCarree()) 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) ax.set_boundary(circle, transform=ax.transAxes, use_as_clip_path=True) # add data # add cyclic point to wrap around in longitude (cartopy function); outputs as np array # if using pyplot: ibase,ilon = user_addcyclic(z,np.array(lon)) cyclic_z, cyclic_lon = add_cyclic_point(z, coord=zlon) cplot = ax.contourf(cyclic_lon, zlat, cyclic_z, transform=ccrs.PlateCarree(), extend='both', levels=levs, cmap=cols) plt.title(title, fontsize=18) # shade OUT non-significance if type(zsig) is int: # default, no significance shown zsig = np.zeros([len(zlat),len(zlon)]) cyclic_zsig, cyclic_tlon = add_cyclic_point(zsig, coord=zlon) cplot_t = ax.contourf(cyclic_lon, zlat, cyclic_zsig, transform=ccrs.PlateCarree(),levels=[-1,0,1],hatches=[None,'..'],colors='none') # colorbar cbar=plt.colorbar(cplot, orientation='vertical', ticks=cbarticks) cbar.set_label(clabel, size=14) cbar.ax.tick_params(labelsize=14) plt.savefig(outname) plt.close()
def test_cartopy_projection(self): cube = iris.load_cube( tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))) projections = {} projections['RotatedPole'] = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) projections['Robinson'] = ccrs.Robinson() projections['PlateCarree'] = ccrs.PlateCarree() projections['NorthPolarStereo'] = ccrs.NorthPolarStereo() projections['Orthographic'] = ccrs.Orthographic(central_longitude=-90, central_latitude=45) projections[ 'InterruptedGoodeHomolosine'] = ccrs.InterruptedGoodeHomolosine() projections['LambertCylindrical'] = ccrs.LambertCylindrical() # Set up figure fig = plt.figure(figsize=(10, 10)) gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=3, hspace=1.5, wspace=0.5) for subplot_spec, (name, target_proj) in itertools.izip( gs, projections.iteritems()): # Set up axes and title ax = plt.subplot(subplot_spec, frameon=False, projection=target_proj) ax.set_title(name) # Transform cube to target projection new_cube, extent = iris.analysis.cartography.project(cube, target_proj, nx=150, ny=150) # Plot plt.pcolor( new_cube.coord('projection_x_coordinate').points, new_cube.coord('projection_y_coordinate').points, new_cube.data) # Add coastlines ax.coastlines() # Tighten up layout gs.tight_layout(plt.gcf()) # Verify resulting plot self.check_graphic(tol=6e-4)
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 test_cursor_values(): ax = plt.axes(projection=ccrs.NorthPolarStereo()) x, y = np.array([-969100.]), np.array([-4457000.]) r = ax.format_coord(x, y) assert_equal(r.encode('ascii', 'ignore'), '-9.691e+05, -4.457e+06 (50.716617N, 12.267069W)') ax = plt.axes(projection=ccrs.PlateCarree()) x, y = np.array([-181.5]), np.array([50.]) r = ax.format_coord(x, y) assert_equal(r.encode('ascii', 'ignore'), '-181.5, 50 (50.000000N, 178.500000E)') ax = plt.axes(projection=ccrs.Robinson()) x, y = np.array([16060595.2]), np.array([2363093.4]) r = ax.format_coord(x, y) assert_equal(r.encode('ascii', 'ignore'), '1.606e+07, 2.363e+06 (22.095524N, 173.709136E)')
def test_barbs_1d_transformed(): x = np.array([20., 30., -17., 15.]) y = np.array([-1., 35., 11., 40.]) u = np.array([23., -18., 2., -11.]) v = np.array([5., -4., 19., 11.]) plot_extent = [-20, 31, -5, 45] plt.figure(figsize=(6, 5)) ax = plt.axes(projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.barbs(x, y, u, v, transform=ccrs.PlateCarree(), length=8, linewidth=1, color='#7f7f7f')
def test_barbs(): x = np.arange(-60, 45, 5) y = np.arange(30, 75, 5) x2d, y2d = np.meshgrid(x, y) u = 40 * np.cos(np.deg2rad(y2d)) v = 40 * np.cos(2. * np.deg2rad(x2d)) plot_extent = [-60, 40, 30, 70] plt.figure(figsize=(6, 6)) # plot on native projection ax = plt.subplot(211, projection=ccrs.PlateCarree()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines(resolution="110m") ax.barbs(x, y, u, v, length=4, linewidth=.25) # plot on a different projection ax = plt.subplot(212, projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines(resolution="110m") ax.barbs(x, y, u, v, transform=ccrs.PlateCarree(), length=4, linewidth=.25)
def test_cursor_values(): ax = plt.axes(projection=ccrs.NorthPolarStereo()) x, y = np.array([-969100., -4457000.]) r = ax.format_coord(x, y) assert (r.encode('ascii', 'ignore') == b'-9.691e+05, -4.457e+06 (50.716617N, 12.267069W)') ax = plt.axes(projection=ccrs.PlateCarree()) x, y = np.array([-181.5, 50.]) r = ax.format_coord(x, y) assert (r.encode('ascii', 'ignore') == b'-181.5, 50 (50.000000N, 178.500000E)') ax = plt.axes(projection=ccrs.Robinson()) x, y = np.array([16060595.2, 2363093.4]) r = ax.format_coord(x, y) assert re.search(b'1.606e\\+07, 2.363e\\+06 ' b'\\(22.09[0-9]{4}N, 173.70[0-9]{4}E\\)', r.encode('ascii', 'ignore'))
def test_quiver_plate_carree(): x = np.arange(-60, 42.5, 2.5) y = np.arange(30, 72.5, 2.5) x2d, y2d = np.meshgrid(x, y) u = np.cos(np.deg2rad(y2d)) v = np.cos(2. * np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 plot_extent = [-60, 40, 30, 70] plt.figure(figsize=(6, 6)) # plot on native projection ax = plt.subplot(211, projection=ccrs.PlateCarree()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines(resolution="110m") ax.quiver(x, y, u, v, mag) # plot on a different projection ax = plt.subplot(212, projection=ccrs.NorthPolarStereo()) ax.set_extent(plot_extent, crs=ccrs.PlateCarree()) ax.coastlines() ax.quiver(x, y, u, v, mag, transform=ccrs.PlateCarree())