def geoplot_sub(rlat, rlon, var, fig, pos, title, type=1, res=30): rotated_pole = ccrs.RotatedPole(pole_longitude=-162.0, pole_latitude=39.25) ax = fig.add_subplot(pos, projection=rotated_pole) ax.add_feature(cpf.OCEAN) ax.add_feature(cpf.COASTLINE) ax.add_feature(cpf.BORDERS, linestyle=':') ax.set_title(title) if type == 1: res = plt.contourf(rlon, rlat, var, res, transform=rotated_pole) if type == 2: ax.set_extent(norway_rotated_pole, crs=rotated_pole) res = plt.pcolormesh(rlon, rlat, var, transform=rotated_pole) return res
def test_new_coords_transposed(self): u, v = self._uv_cubes_limited_extent() # Transpose cubes so that cube is in xy order rather than the # typical yx order of meshgrid. u.transpose() v.transpose() x = u.coord("grid_longitude").points y = u.coord("grid_latitude").points x2d, y2d = np.meshgrid(x, y) src_crs = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) tgt_crs = ccrs.OSGB() xyz_tran = tgt_crs.transform_points(src_crs, x2d, y2d) ut, vt = rotate_winds(u, v, iris.coord_systems.OSGB()) points = xyz_tran[..., 0].reshape(x2d.shape) expected_x = AuxCoord( points, standard_name="projection_x_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_x_coordinate"), expected_x) self.assertEqual(vt.coord("projection_x_coordinate"), expected_x) points = xyz_tran[..., 1].reshape(y2d.shape) expected_y = AuxCoord( points, standard_name="projection_y_coordinate", units="m", coord_system=iris.coord_systems.OSGB(), ) self.assertEqual(ut.coord("projection_y_coordinate"), expected_y) self.assertEqual(vt.coord("projection_y_coordinate"), expected_y) # Check dim mapping for 2d coords is yx. expected_dims = u.coord_dims("grid_latitude") + u.coord_dims( "grid_longitude" ) self.assertEqual( ut.coord_dims("projection_x_coordinate"), expected_dims ) self.assertEqual( ut.coord_dims("projection_y_coordinate"), expected_dims ) self.assertEqual( vt.coord_dims("projection_x_coordinate"), expected_dims ) self.assertEqual( vt.coord_dims("projection_y_coordinate"), expected_dims )
def main(): rotated_crs = ccrs.RotatedPole(pole_longitude=120.0, pole_latitude=70.0) ax0 = plt.axes(projection=rotated_crs) ax0.set_extent([-6, 1, 47.5, 51.5], crs=ccrs.PlateCarree()) ax0.add_feature(cfeature.LAND.with_scale('110m')) ax0.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False) plt.figure(figsize=(6.9228, 3)) ax1 = plt.axes(projection=ccrs.InterruptedGoodeHomolosine()) ax1.coastlines(resolution='110m') ax1.gridlines(draw_labels=True) plt.show()
def test_mapping(): import cartopy.crs as ccrs eur11 = cx.cordex_domain('EUR-11') pole = (eur11.rotated_latitude_longitude.grid_north_pole_longitude, eur11.rotated_latitude_longitude.grid_north_pole_latitude) lon1, lat1 = cx.rotated_coord_transform(eur11.rlon, eur11.rlat, *pole, direction="rot2geo") transform = ccrs.RotatedPole(-162.0, 39.25) lon2, lat2 = cx.map_crs(eur11.rlon, eur11.rlat, transform) assert (np.allclose(lon1, lon2)) assert (np.allclose(lat1, lat2))
def contour2(infile, varname, title): """*Plot 2* Contour-plot with user defined colors, contour levels and as pdf output. **Arguments:** *infile:* Path of the File/ Netcdf to read. *varname:* Name of the variable to read. *title:* Title of the figure as string. **Returns:** *plot* Returns a pdf with the contour-plot. """ #read netcdf and select variable var, rot_pole = read_nc(infile, varname) #levels, colors, label clevs, col, label = level_color_label(varname) fig = plt.figure(figsize=(10, 8)) #Rotated pole projection with Cartopy rotated_pole = ccrs.RotatedPole(pole_latitude=rot_pole[0], pole_longitude=rot_pole[1]) ax = plt.axes(projection=rotated_pole) #printing coastlines ax.coastlines(resolution='50m', color='black', linewidth=1) #Country boarders ax.add_feature(cfeature.BORDERS) #setting gridlines ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, y_inline=False, x_inline=False) #Actual Plot var.plot(ax=ax, vmin=0, transform=rotated_pole, cmap=col, levels=clevs[0], cbar_kwargs=dict(orientation='vertical', pad=0.1, shrink=1, label=label)) ax.set_title(title) fig.savefig(title + '.pdf')
def Plot_on_Segments(Scalar_Field, Variable_Name, year, month, day, hour, forecast_period, num_cells, filename='plot'): """ Plot some field associated with the different segments. """ #Load a single instance of the data set so that we can get the latitude and longitude coordinates: f = mogreps.download_data('mogreps-uk', mogreps.make_data_object_name( 'mogreps-uk', year, Month_Map(month), day, hour, 0, forecast_period), data_folder=Path('.')) data_set = netCDF4.Dataset(f) rotation = data_set['rotated_latitude_longitude'] transform = ccrs.RotatedPole( pole_longitude=rotation.grid_north_pole_longitude, pole_latitude=rotation.grid_north_pole_latitude) projection = transform fig = plt.figure(figsize=(20, 10)) #create an axis instance: ax = fig.add_subplot(111, projection=projection) pcm = ax.pcolormesh(data_set['grid_longitude'], data_set['grid_latitude'], Scalar_Field, transform=transform, cmap='jet') ax.coastlines(resolution='10m') #ax.colorbar() colbar = fig.colorbar(pcm) #ax.imshow(mark_boundaries(image, segments)) #colbar.set_label("VAR(" + str(variable_name) + ")") plt.title(Variable_Name + " " + str(year) + "_" + month + "_" + str(day) + "_" + str(hour) + "_forcast_period=" + str(forecast_period)) plt.savefig(filename + "_" + str(year) + "_" + month + "_" + str(day) + "_h_" + str(hour) + "_fp_" + str(forecast_period) + "_cells_" + str(num_cells), bbox_inches='tight') plt.show()
def main(): rotated_crs = ccrs.RotatedPole(pole_longitude=120.0, pole_latitude=70.0) ax0 = plt.axes(projection=rotated_crs) ax0.set_extent([-6, 1, 47.5, 51.5], crs=ccrs.PlateCarree()) ax0.add_feature(cfeature.LAND.with_scale('110m')) ax0.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False) plt.figure(figsize=(6.9228, 3)) ax1 = plt.axes(projection=ccrs.InterruptedGoodeHomolosine()) ax1.coastlines(resolution='110m') ax1.gridlines(draw_labels=True) plt.figure(figsize=(7, 3)) ax2 = plt.axes(projection=ccrs.PlateCarree()) ax2.coastlines(resolution='110m') gl = ax2.gridlines(draw_labels=True) gl.top_labels = False gl.right_labels = False plt.show() plt.figure(figsize=(7, 3)) ax3 = plt.axes(projection=ccrs.PlateCarree()) ax3.set_extent([-65, -40, -15, 10]) # Create a feature for States/Admin 1 regions at 1:50m from Natural Earth states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax3.add_feature(states_provinces, edgecolor='gray') ax3.coastlines(resolution='110m') ax3.coastlines(resolution='110m') gl = ax3.gridlines(draw_labels=True) gl.change_gridline_tick_decimal_separator('{0:.3f}', axis='both') gl.set_latitude_hemisphere_str('Norte', 'Sul') gl.set_longitude_hemisphere_str('O', 'L') gl.top_labels = False gl.right_labels = False plt.show() return plt.gcf().get_axes(), gl
def test_pcolormesh_limited_area_wrap(): # make up some realistic data with bounds (such as data from the UM's North # Atlantic Europe model) nx, ny = 22, 36 xbnds = np.linspace(311.91998291, 391.11999512, nx, endpoint=True) ybnds = np.linspace(-23.59000015, 24.81000137, ny, endpoint=True) x, y = np.meshgrid(xbnds, ybnds) data = ((np.sin(np.deg2rad(x))) / 10. + np.exp(np.cos(np.deg2rad(y)))) data = data[:-1, :-1] rp = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) plt.figure(figsize=(10, 6)) ax = plt.subplot(221, projection=ccrs.PlateCarree()) plt.pcolormesh(xbnds, ybnds, data, transform=rp, cmap='Spectral', snap=False) ax.coastlines() ax = plt.subplot(222, projection=ccrs.PlateCarree(180)) plt.pcolormesh(xbnds, ybnds, data, transform=rp, cmap='Spectral', snap=False) ax.coastlines() ax.set_global() # draw the same plot, only more zoomed in, and using the 2d versions # of the coordinates (just to test that 1d and 2d are both suitably # being fixed) ax = plt.subplot(223, projection=ccrs.PlateCarree()) plt.pcolormesh(x, y, data, transform=rp, cmap='Spectral', snap=False) ax.coastlines() ax.set_extent([-70, 0, 0, 80]) ax = plt.subplot(224, projection=rp) plt.pcolormesh(xbnds, ybnds, data, transform=rp, cmap='Spectral', snap=False) ax.coastlines()
def findProjectedPosition(self, pos, star): # Check inside disk if np.sqrt(pos[0]**2 + pos[1]**2) <= 1: # Scale calculated X,Y to actual star radius pos *= star.radius # Use CartoPy to transform from Ortho coords unitPole = ccrs.RotatedPole(pole_longitude=180, pole_latitude=90, central_rotated_longitude=0, globe=star.globe) return unitPole.transform_points(star.orth_proj, np.asarray([pos[0]]), np.asarray([pos[1]]))[:, 0:2][0] else: return np.nan
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 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 test_other_projection(self): # Check it still works with a different target projection. test_proj = ccrs.RotatedPole(pole_longitude=107.3, pole_latitude=-37.1) extent = [-180, 180, -75., 75.] target_dims_xy = (7, 5) result, = self._raster.fetch_raster( projection=test_proj, extent=extent, target_resolution=target_dims_xy) result = result.image expected = np.array([[2.75, 2.75, 3., 3., 2.75, 3., 2.75], [2.75, 2.75, 2., 4., 0., -0.25, 2.75], [5., 2., 2., 3.75, 0., 5., 5.], [4.75, 2., 1.75, 0.75, 0.75, 0.75, 4.75], [4.75, 5., 5., 0.75, 0.75, 1., 4.75]]) self.assertArrayAllClose(result, expected)
def _ensure_cartopy_axes_and_determine_kwargs(x_coord, y_coord, kwargs): """ Replace the current non-cartopy axes with :class:`cartopy.mpl.GeoAxes` and return the appropriate kwargs dict based on the provided coordinates and kwargs. """ # Determine projection. if x_coord.coord_system != y_coord.coord_system: raise ValueError('The X and Y coordinates must have equal coordinate' ' systems.') cs = x_coord.coord_system if cs is not None: cartopy_proj = cs.as_cartopy_projection() else: cartopy_proj = ccrs.PlateCarree() # Ensure the current axes are a cartopy.mpl.GeoAxes instance. axes = kwargs.get('axes') if axes is None: if (isinstance(cs, iris.coord_systems.RotatedGeogCS) and x_coord.points.max() > 180 and x_coord.points.max() < 360 and x_coord.points.min() > 0): # The RotatedGeogCS has 0 - 360 extent, different from the # assumptions made by Cartopy: rebase longitudes for the map axes # to set the datum longitude to the International Date Line. cs_kwargs = cs._ccrs_kwargs() cs_kwargs['central_rotated_longitude'] = 180.0 adapted_cartopy_proj = ccrs.RotatedPole(**cs_kwargs) _replace_axes_with_cartopy_axes(adapted_cartopy_proj) else: _replace_axes_with_cartopy_axes(cartopy_proj) elif axes and not isinstance(axes, cartopy.mpl.geoaxes.GeoAxes): raise TypeError("The supplied axes instance must be a cartopy " "GeoAxes instance.") # Set the "from transform" keyword. if 'transform' in kwargs: raise ValueError("The 'transform' keyword is not allowed as it " "automatically determined from the coordinate " "metadata.") new_kwargs = kwargs.copy() new_kwargs['transform'] = cartopy_proj return new_kwargs
def sample_data(shape=(20, 30)): """ Returns ``(x, y, u, v, crs)`` of some vector data computed mathematically. The returned crs will be a rotated pole CRS, meaning that the vectors will be unevenly spaced in regular PlateCarree space. """ crs = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) x = np.linspace(311.9, 391.1, shape[1]) y = np.linspace(-23.6, 24.8, shape[0]) x2d, y2d = np.meshgrid(x, y) u = 10 * (2 * np.cos(2 * np.deg2rad(x2d) + 3 * np.deg2rad(y2d + 30))**2) v = 20 * np.cos(6 * np.deg2rad(x2d)) return x, y, u, v, crs
def plot_data(lat, lon, tec, titlestr, axext=[-180, 180, 45, 90]): # set up the plot ax = plt.axes(projection=ccrs.Orthographic(-10, 45)) crs = ccrs.RotatedPole(pole_longitude=0, pole_latitude=70) ax.add_feature(cartopy.feature.OCEAN, zorder=0) ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black') ax.set_global() # make the plot lon[lon > 180] -= 360 plt.contourf(lon, lat, tec, transform=crs) ax.gridlines() plt.suptitle(titlestr) plt.show()
def __init__(self, nx, ny, dx, dy, xmin, ymin, pollon, pollat): """Store the grid information. Parameters ---------- nx : int Number of cells in longitudinal direction ny : int Number of cells in latitudinal direction dx : float Longitudinal size of a gridcell in degrees dy : float Latitudinal size of a gridcell in degrees xmin : float Longitude of bottom left gridpoint in degrees ymin : float Latitude of bottom left gridpoint in degrees pollon : float Longitude of the rotated pole pollat : float Latitude of the rotated pole """ self.nx = nx self.ny = ny self.dx = dx self.dy = dy self.xmin = xmin self.ymin = ymin self.pollon = pollon self.pollat = pollat # cell corners x = self.xmin + np.arange(self.nx) * self.dx y = self.ymin + np.arange(self.ny) * self.dy dx2 = self.dx / 2 dy2 = self.dy / 2 self.cell_x = np.array([x + dx2, x + dx2, x - dx2, x - dx2]) self.cell_y = np.array([y + dy2, y - dy2, y - dy2, y + dy2]) super().__init__( "COSMO", ccrs.RotatedPole(pole_longitude=pollon, pole_latitude=pollat), )
def main(): rp = ccrs.RotatedPole(pole_latitude=45, pole_longitude=180) pc = ccrs.PlateCarree() ax = plt.subplot(211, projection=rp) ax.bluemarble() ax.coastlines() x, y = [-44, -44, 45, 45, -44], [-45, 45, 45, -45, -45] ax.plot(x, y, marker='o', transform=rp) ax.fill(x, y, color='coral', transform=rp, alpha=0.4) ax.gridlines(15) ax = plt.subplot(212, projection=pc) ax.bluemarble() ax.coastlines() ax.plot(x, y, transform=rp) ax.fill(x, y, transform=rp, color='coral', alpha=0.4) ax.gridlines(15) plt.show()
def test_view_lim_autoscaling(): x = np.linspace(0.12910209, 0.42141822) y = np.linspace(0.03739792, 0.33029076) x, y = np.meshgrid(x, y) ax = plt.axes(projection=ccrs.RotatedPole(37.5, 357.5)) plt.scatter(x, y, x * y, transform=ccrs.PlateCarree()) expected = np.array([[86.12433701, 52.51570463], [86.69696603, 52.86372057]]) assert_array_almost_equal(ax.viewLim.frozen().get_points(), expected) plt.draw() assert_array_almost_equal(ax.viewLim.frozen().get_points(), expected) ax.relim() ax.autoscale_view(tight=False) expected_non_tight = np.array([[86, 52.45], [86.8, 52.9]]) assert_array_almost_equal(ax.viewLim.frozen().get_points(), expected_non_tight)
def pressure_plots(test_variable, v_min, v_max): rotation = forecasts[0]['rotated_latitude_longitude'] transform = ccrs.RotatedPole( pole_longitude=rotation.grid_north_pole_longitude, pole_latitude=rotation.grid_north_pole_latitude) projection = transform fig = plt.figure(figsize=(20, 10)) for i in range(0, 6): ax = fig.add_subplot(2, 3, i + 1, projection=projection) pcm = ax.pcolormesh(forecasts[i]['grid_longitude'], forecasts[i]['grid_latitude'], forecasts[i][test_variable][2], transform=transform, vmin=97000, vmax=103000, cmap='seismic') ax.coastlines(resolution='10m') ax.set_title(str(6 * (i + 1) - 3) + " hours") plt.colorbar(pcm, ax=ax)
def test_pcolormesh_single_column_wrap(): # Check a wrapped mesh like test_pcolormesh_limited_area_wrap, but only use # a single column, which could break depending on how wrapping is # determined. ny = 36 xbnds = np.array([360.9485619, 364.71999105]) ybnds = np.linspace(-23.59000015, 24.81000137, ny, endpoint=True) x, y = np.meshgrid(xbnds, ybnds) data = ((np.sin(np.deg2rad(x))) / 10. + np.exp(np.cos(np.deg2rad(y)))) data = data[:-1, :-1] rp = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) plt.figure(figsize=(10, 6)) ax = plt.subplot(111, projection=ccrs.PlateCarree(180)) plt.pcolormesh(xbnds, ybnds, data, transform=rp, cmap='Spectral') ax.coastlines() ax.set_global()
def test_self_intersecting_1(self): # Geometry comes from a matplotlib contourf (see #537) wkt = ('POLYGON ((366.22000122 -9.71489298, ' '366.73212393 -9.679999349999999, ' '366.77412634 -8.767753000000001, ' '366.17762962 -9.679999349999999, ' '366.22000122 -9.71489298), ' '(366.22000122 -9.692636309999999, ' '366.32998657 -9.603356099999999, ' '366.74765799 -9.019999500000001, ' '366.5094086 -9.63175386, ' '366.22000122 -9.692636309999999))') geom = shapely.wkt.loads(wkt) source, target = ccrs.RotatedPole(198.0, 39.25), ccrs.EuroPP() projected = target.project_geometry(geom, source) # Before handling self intersecting interiors, the area would be # approximately 13262233761329. area = projected.area self.assertTrue(2.2e9 < area < 2.3e9, msg='Got area {}, expecting ~2.2e9'.format(area))
def rotpole2wgs(rlon, rlat, pollon, pollat, inverse=False): """ Transform rotated pole to WGS84. """ c_in = ccrs.RotatedPole(pollon, pollat) c_out = ccrs.PlateCarree() if inverse: c_in, c_out = c_out, c_in if np.ndim(rlon) == 0: res = c_out.transform_point(rlon, rlat, c_in) return res[0], res[1] elif np.ndim(rlon) in [1, 2]: res = c_out.transform_points(c_in, rlon, rlat) return res[..., 0], res[..., 1] else: shape = rlon.shape res = c_out.transform_points(c_in, rlon.flatten(), rlat.flatten()) return res[:, 0].reshape(shape), res[:, 1].reshape(shape)
def test_quiver_rotated_pole(): nx, ny = 22, 36 x = np.linspace(311.91998291, 391.11999512, nx, endpoint=True) y = np.linspace(-23.59000015, 24.81000137, ny, endpoint=True) x2d, y2d = np.meshgrid(x, y) u = np.cos(np.deg2rad(y2d)) v = -2. * np.cos(2. * np.deg2rad(y2d)) * np.sin(np.deg2rad(x2d)) mag = (u**2 + v**2)**.5 rp = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) plot_extent = [x[0], x[-1], y[0], y[-1]] # plot on native projection plt.figure(figsize=(6, 6)) ax = plt.subplot(211, projection=rp) ax.set_extent(plot_extent, crs=rp) ax.coastlines() ax.quiver(x, y, u, v, mag) # plot on different projection ax = plt.subplot(212, projection=ccrs.PlateCarree()) ax.set_extent(plot_extent, crs=rp) ax.coastlines() ax.quiver(x, y, u, v, mag, transform=rp)
def main(): rotated_pole = ccrs.RotatedPole(pole_latitude=45, pole_longitude=180) box_top = 45 x, y = [-44, -44, 45, 45, -44], [-45, box_top, box_top, -45, -45] ax = plt.subplot(211, projection=rotated_pole) ax.stock_img() ax.coastlines() ax.plot(x, y, marker='o', transform=rotated_pole) ax.fill(x, y, color='coral', transform=rotated_pole, alpha=0.4) ax.gridlines() ax = plt.subplot(212, projection=ccrs.PlateCarree()) ax.stock_img() ax.coastlines() ax.plot(x, y, marker='o', transform=rotated_pole) ax.fill(x, y, transform=rotated_pole, color='coral', alpha=0.4) ax.gridlines() plt.show()
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(), ] fig = plt.figure(figsize=(10, 10)) for i, prj in enumerate(projections, 1): ax = fig.add_subplot(5, 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 get_cartopy_proj_and_coords(self): """ :return: lons2d, lats2d, basemap [based on the bathymetry file and gemclim_settings.nml] """ from cartopy import crs # Read longitudes and latitudes and create the basemap only if they are not initialized if self.ccrs is None: with Dataset(os.path.join(self.data_folder, self.bathymetry_file)) as ds: self.lons, self.lats = ds.variables["nav_lon"][:].transpose( ), ds.variables["nav_lat"][:].transpose() import re lon1, lat1 = None, None lon2, lat2 = None, None with open(os.path.join(self.data_folder, self.proj_file)) as f: for line in f: if "Grd_xlat1" in line and "Grd_xlon1" in line: groups = re.findall(r"-?\b\d+.?\d*\b", line) lat1, lon1 = [float(s) for s in groups] if "Grd_xlat2" in line and "Grd_xlon2" in line: groups = re.findall(r"-?\b\d+.?\d*\b", line) lat2, lon2 = [float(s) for s in groups] rll = RotatedLatLon(lon1=lon1, lat1=lat1, lon2=lon2, lat2=lat2) # self.basemap = rll.get_basemap_object_for_lons_lats(lons2d=self.lons, lats2d=self.lats) lon0, _ = rll.get_true_pole_coords_in_rotated_system() o_lon_p, o_lat_p = rll.get_north_pole_coords() print(lon0, o_lat_p) self.ccrs = crs.RotatedPole(pole_longitude=lon0, pole_latitude=o_lat_p) self.lons[self.lons > 180] -= 360 return self.lons, self.lats, self.ccrs
def fill_dark_side(ax, time=None, **kwargs): """ Plot a fill on the dark side of the planet (without refraction). Parameters ---------- ax : Matplotlib axes The axes to plot on. time : datetime The time to calculate terminator for. Defaults to datetime.utcnow() **kwargs : Passed on to Matplotlib's ax.fill() """ import cartopy.crs as ccrs lat, lng = sun_pos(time) pole_lng = lng if lat > 0: pole_lat = -90 + lat central_rot_lng = 180 else: pole_lat = 90 + lat central_rot_lng = 0 rotated_pole = ccrs.RotatedPole(pole_latitude=pole_lat, pole_longitude=pole_lng, central_rotated_longitude=central_rot_lng) x = np.empty(360) y = np.empty(360) x[:180] = -90 y[:180] = np.arange(-90, 90.) x[180:] = 90 y[180:] = np.arange(90, -90., -1) ax.fill(x, y, transform=rotated_pole, **kwargs)
aspect = 16 / 9.0 fig = Figure( figsize=(22, 22 / aspect), # Width, Height (inches) dpi=100, facecolor=(0.88, 0.88, 0.88, 1), edgecolor=None, linewidth=0.0, frameon=False, # Don't draw a frame subplotpars=None, tight_layout=None) # Attach a canvas canvas = FigureCanvas(fig) # All mg plots use Rotated Pole, in this case just use the standard # pole location. projection = ccrs.RotatedPole(pole_longitude=180.0, pole_latitude=90.0) # Define an axes to contain the plot. In this case our axes covers # the whole figure ax = fig.add_axes([0, 0, 1, 1], projection=projection) ax.set_axis_off() # Don't want surrounding x and y axis # Set the axes background colour ax.background_patch.set_facecolor((0.88, 0.88, 0.88, 1)) # Lat and lon range (in rotated-pole coordinates) for plot extent = [-180.0, 180.0, -90.0, 90.0] ax.set_extent(extent, crs=projection) # Lat:Lon aspect does not match the plot aspect, ignore this and # fill the figure with the plot. matplotlib.rc('image', aspect='auto')
def test_something(self): projection = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) line_string = sgeom.LineString([(0, 0), (1e-14, 0)]) multi_line_string = projection.project_geometry(line_string) assert len(multi_line_string) == 1 assert len(multi_line_string[0].coords) == 2