def test_wms(): ax = plt.axes(projection=ccrs.Orthographic()) url = 'http://vmap0.tiles.osgeo.org/wms/vmap0' layer = 'basic' ax.add_wms(url, layer)
#---------------------- # Figure setup #---------------------- dpi, scale = 200, 2.6 fig = plt.figure(figsize=(2.5 * scale, 1.3 * scale)) gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1.2]) a = 0.04 gs.update(left=a, right=1 - a, top=0.95, bottom=0.16, wspace=0.015 * 18, hspace=0.25) prj = ccrs.Orthographic(rot, 90 - inclination) geo = ccrs.Geodetic() axdistr = plt.subplot(gs[0, 0], projection=prj) axeigvals = plt.subplot(gs[0, 1]) axdistr.set_global() # show entire S^2 #---------------------- # n(theta,phi) on S^2 #---------------------- lvls = np.arange(0, 0.2 + 1e-5, 0.025) # Contour lvls F = np.real( np.sum([ c[tt, ii] * sp.sph_harm(m, l, phi, theta)
#plt.figure(2) #plt.imshow(pimg,vmin=0, vmax=100,cmap=aurora_cmap()) #plt.imshow(pimg,vmin=0, vmax=100,cmap=aurora_cmap()) plt.figure(1) plt.plot(pimg) fig = plt.figure(2, figsize=[20, 10]) # We choose to plot in an Orthographic projection as it looks natural # and the distortion is relatively small around the poles where # the aurora is most likely. # ax1 for Northern Hemisphere ax1 = fig.add_subplot(1, 2, 1, projection=ccrs.Orthographic(0, 60)) # class cartopy.crs.Orthographic(central_longitude=0.0, central_latitude=0.0, globe=None)[source] # ax2 for Southern Hemisphere ax2 = fig.add_subplot(1, 2, 2, projection=ccrs.Orthographic(-100, 60)) #img, crs, extent, origin, dt = aurora_forecast() fig.set_facecolor((0, 0, 0)) url = 'https://map1c.vis.earthdata.nasa.gov/wmts-geo/wmts.cgi' layer = 'VIIRS_CityLights_2012' for ax in [ax1, ax2]: ax.coastlines(zorder=3, color='grey', alpha=0.9) ax.add_feature(carfeat.BORDERS, zorder=3, alpha=0.9)
def PlateCarree_to_Orthographic(img, llbd, craters, iglobe=None, ctr_sub=False, arad=1737.4, origin="upper", rgcoeff=1.2, slivercut=0.): """Transform Plate Carree image and associated csv file into Orthographic. Parameters ---------- img : PIL.Image.image or str File or filename. llbd : list-like Long/lat limits (long_min, long_max, lat_min, lat_max) of image. craters : pandas.DataFrame Craters catalogue. iglobe : cartopy.crs.Geodetic instance Globe for images. If False, defaults to spherical Moon. ctr_sub : bool, optional If `True`, assumes craters dataframe includes only craters within image. If `False` (default_, llbd used to cut craters from outside image out of (copy of) dataframe. arad : float World radius in km. Default is Moon (1737.4 km). origin : "lower" or "upper", optional Based on imshow convention for displaying image y-axis. "upper" (default) means that [0,0] is upper-left corner of image; "lower" means it is bottom-left. rgcoeff : float, optional Fractional size increase of transformed image height. By default set to 1.2 to prevent loss of fidelity during transform (though warping can be so extreme that this might be meaningless). slivercut : float from 0 to 1, optional If transformed image aspect ratio is too narrow (and would lead to a lot of padding, return null images). Returns ------- imgo : PIL.Image.image Transformed, padded image in PIL.Image format. ctr_xy : pandas.DataFrame Craters with transformed x, y pixel positions and pixel radii. distortion_coefficient : float Ratio between the central heights of the transformed image and original image. centrallonglat_xy : pandas.DataFrame xy position of the central longitude and latitude. """ # If user doesn't provide Moon globe properties. if not iglobe: iglobe = ccrs.Globe(semimajor_axis=arad*1000., semiminor_axis=arad*1000., ellipse=None) # Set up Geodetic (long/lat), Plate Carree (usually long/lat, but not when # globe != WGS84) and Orthographic projections. geoproj = ccrs.Geodetic(globe=iglobe) iproj = ccrs.PlateCarree(globe=iglobe) oproj = ccrs.Orthographic(central_longitude=np.mean(llbd[:2]), central_latitude=np.mean(llbd[2:]), globe=iglobe) # Create and transform coordinates of image corners and edge midpoints. # Due to Plate Carree and Orthographic's symmetries, max/min x/y values of # these 9 points represent extrema of the transformed image. xll = np.array([llbd[0], np.mean(llbd[:2]), llbd[1]]) yll = np.array([llbd[2], np.mean(llbd[2:]), llbd[3]]) xll, yll = np.meshgrid(xll, yll) xll = xll.ravel() yll = yll.ravel() # [:,:2] because we don't need elevation data. res = iproj.transform_points(x=xll, y=yll, src_crs=geoproj)[:, :2] iextent = [min(res[:, 0]), max(res[:, 0]), min(res[:, 1]), max(res[:, 1])] res = oproj.transform_points(x=xll, y=yll, src_crs=geoproj)[:, :2] oextent = [min(res[:, 0]), max(res[:, 0]), min(res[:, 1]), max(res[:, 1])] # Sanity check for narrow images; done before the most expensive part of # the function. oaspect = (oextent[1] - oextent[0]) / (oextent[3] - oextent[2]) if oaspect < slivercut: return [None, None, None, None] if type(img) != Image.Image: img = Image.open(img).convert("L") # Warp image. imgo, imgwshp, offset = WarpImagePad(img, iproj, iextent, oproj, oextent, origin=origin, rgcoeff=rgcoeff, fillbg="black") # Convert crater x, y position. if ctr_sub: llbd_in = None else: llbd_in = llbd ctr_xy = WarpCraterLoc(craters, geoproj, oproj, oextent, imgwshp, llbd=llbd_in, origin=origin) # Shift crater x, y positions by offset (origin doesn't matter for y-shift, # since padding is symmetric). ctr_xy.loc[:, "x"] += offset[0] ctr_xy.loc[:, "y"] += offset[1] # Pixel scale for orthographic determined (for images small enough that # tan(x) approximately equals x + 1/3x^3 + ...) by l = R_moon*theta, # where theta is the latitude extent of the centre of the image. Because # projection transform doesn't guarantee central vertical axis will keep # its pixel resolution, we need to calculate the conversion coefficient # C = (res[7,1]- res[1,1])/(oextent[3] - oextent[2]). # C0*pix height/C = theta # Where theta is the latitude extent and C0 is the theta per pixel # conversion for the Plate Carree image). Thus # l_ctr = R_moon*C0*pix_ctr/C. distortion_coefficient = ((res[7, 1] - res[1, 1]) / (oextent[3] - oextent[2])) if distortion_coefficient < 0.7: raise ValueError("Distortion Coefficient cannot be" " {0:.2f}!".format(distortion_coefficient)) pixperkm = trf.km2pix(imgo.size[1], llbd[3] - llbd[2], dc=distortion_coefficient, a=arad) ctr_xy["Diameter (pix)"] = ctr_xy["Diameter (km)"] * pixperkm # Determine x, y position of central lat/long. centrallonglat = pd.DataFrame({"Long": [xll[4]], "Lat": [yll[4]]}) centrallonglat_xy = WarpCraterLoc(centrallonglat, geoproj, oproj, oextent, imgwshp, llbd=llbd_in, origin=origin) # Shift central long/lat centrallonglat_xy.loc[:, "x"] += offset[0] centrallonglat_xy.loc[:, "y"] += offset[1] return [imgo, ctr_xy, distortion_coefficient, centrallonglat_xy]
def plot_cartopy(lons, lats, size, color, labels=None, projection='global', resolution='110m', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, colorbar=None, marker="o", title=None, colorbar_ticklabel_format=None, show=True, proj_kwargs=None, **kwargs): # @UnusedVariable """ Creates a Cartopy plot with a data point scatter plot. :type lons: list/tuple of floats :param lons: Longitudes of the data points. :type lats: list/tuple of floats :param lats: Latitudes of the data points. :type size: float or list/tuple of floats :param size: Size of the individual points in the scatter plot. :type color: list/tuple of floats (or objects that can be converted to floats, like e.g. :class:`~obspy.core.utcdatetime.UTCDateTime`) :param color: Color information of the individual data points to be used in the specified color map (e.g. origin depths, origin times). :type labels: list/tuple of str :param labels: Annotations for the individual data points. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world using :class:`~cartopy.crs.Mollweide`.) * ``"ortho"`` (Will center around the mean lat/long using :class:`~cartopy.crs.Orthographic`.) * ``"local"`` (Will plot around local events using :class:`~cartopy.crs.AlbersEqualArea`.) * Any other Cartopy :class:`~cartopy.crs.Projection`. An instance of this class will be created using the supplied ``proj_kwargs``. Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be passed directly to the Cartopy module. Possible values are: * ``"110m"`` * ``"50m"`` * ``"10m"`` Defaults to ``"110m"``. For compatibility, you may also specify any of the Basemap resolutions defined in :func:`plot_basemap`. :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events as provided in `color` kwarg. The event with the smallest `color` property will have the color of one end of the colormap and the event with the highest `color` property the color of the other end with all other events in between. Defaults to None which will use the default matplotlib colormap. :type colorbar: bool, optional :param colorbar: When left `None`, a colorbar is plotted if more than one object is plotted. Using `True`/`False` the colorbar can be forced on/off. :type title: str :param title: Title above plot. :type colorbar_ticklabel_format: str or function or subclass of :class:`matplotlib.ticker.Formatter` :param colorbar_ticklabel_format: Format string or Formatter used to format colorbar tick labels. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type proj_kwargs: dict :param proj_kwargs: Keyword arguments to pass to the Cartopy :class:`~cartopy.ccrs.Projection`. In this dictionary, you may specify ``central_longitude='auto'`` or ``central_latitude='auto'`` to have this function calculate the latitude or longitude as it would for other projections. Some arguments may be ignored if you choose one of the built-in ``projection`` choices. """ import matplotlib.pyplot as plt if isinstance(color[0], (datetime.datetime, UTCDateTime)): datetimeplot = True color = [date2num(getattr(t, 'datetime', t)) for t in color] else: datetimeplot = False fig = plt.figure() # The colorbar should only be plotted if more then one event is # present. if colorbar is not None: show_colorbar = colorbar else: if len(lons) > 1 and hasattr(color, "__len__") and \ not isinstance(color, (str, native_str)): show_colorbar = True else: show_colorbar = False if projection == "local": ax_x0, ax_width = 0.10, 0.80 elif projection == "global": ax_x0, ax_width = 0.01, 0.98 else: ax_x0, ax_width = 0.05, 0.90 proj_kwargs = proj_kwargs or {} if projection == 'global': proj_kwargs['central_longitude'] = np.mean(lons) proj = ccrs.Mollweide(**proj_kwargs) elif projection == 'ortho': proj_kwargs['central_latitude'] = np.mean(lats) proj_kwargs['central_longitude'] = mean_longitude(lons) proj = ccrs.Orthographic(**proj_kwargs) elif projection == 'local': if min(lons) < -150 and max(lons) > 150: max_lons = max(np.array(lons) % 360) min_lons = min(np.array(lons) % 360) else: max_lons = max(lons) min_lons = min(lons) lat_0 = max(lats) / 2. + min(lats) / 2. lon_0 = max_lons / 2. + min_lons / 2. if lon_0 > 180: lon_0 -= 360 deg2m_lat = 2 * np.pi * 6371 * 1000 / 360 deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi) if len(lats) > 1: height = (max(lats) - min(lats)) * deg2m_lat width = (max_lons - min_lons) * deg2m_lon margin = 0.2 * (width + height) height += margin width += margin else: height = 2.0 * deg2m_lat width = 5.0 * deg2m_lon # Do intelligent aspect calculation for local projection # adjust to figure dimensions w, h = fig.get_size_inches() aspect = w / h if show_colorbar: aspect *= 1.2 if width / height < aspect: width = height * aspect else: height = width / aspect proj_kwargs['central_latitude'] = lat_0 proj_kwargs['central_longitude'] = lon_0 proj = ccrs.AlbersEqualArea(**proj_kwargs) # User-supplied projection. elif isinstance(projection, type): if 'central_longitude' in proj_kwargs: if proj_kwargs['central_longitude'] == 'auto': proj_kwargs['central_longitude'] = mean_longitude(lons) if 'central_latitude' in proj_kwargs: if proj_kwargs['central_latitude'] == 'auto': proj_kwargs['central_latitude'] = np.mean(lats) if 'pole_longitude' in proj_kwargs: if proj_kwargs['pole_longitude'] == 'auto': proj_kwargs['pole_longitude'] = np.mean(lons) if 'pole_latitude' in proj_kwargs: if proj_kwargs['pole_latitude'] == 'auto': proj_kwargs['pole_latitude'] = np.mean(lats) proj = projection(**proj_kwargs) else: msg = "Projection '%s' not supported." % projection raise ValueError(msg) if show_colorbar: map_ax = fig.add_axes([ax_x0, 0.13, ax_width, 0.77], projection=proj) cm_ax = fig.add_axes([ax_x0, 0.05, ax_width, 0.05]) plt.sca(map_ax) else: ax_y0, ax_height = 0.05, 0.85 if projection == "local": ax_y0 += 0.05 ax_height -= 0.05 map_ax = fig.add_axes([ax_x0, ax_y0, ax_width, ax_height], projection=proj) if projection == 'local': x0, y0 = proj.transform_point(lon_0, lat_0, proj.as_geodetic()) map_ax.set_xlim(x0 - width / 2, x0 + width / 2) map_ax.set_ylim(y0 - height / 2, y0 + height / 2) else: map_ax.set_global() # Pick features at specified resolution. resolution = _CARTOPY_RESOLUTIONS[resolution] try: borders, land, ocean = _CARTOPY_FEATURES[resolution] except KeyError: borders = cfeature.NaturalEarthFeature(cfeature.BORDERS.category, cfeature.BORDERS.name, resolution, edgecolor='none', facecolor='none') land = cfeature.NaturalEarthFeature(cfeature.LAND.category, cfeature.LAND.name, resolution, edgecolor='face', facecolor='none') ocean = cfeature.NaturalEarthFeature(cfeature.OCEAN.category, cfeature.OCEAN.name, resolution, edgecolor='face', facecolor='none') _CARTOPY_FEATURES[resolution] = (borders, land, ocean) # Draw coast lines, country boundaries, fill continents. if MATPLOTLIB_VERSION >= [2, 0, 0]: map_ax.set_facecolor(water_fill_color) else: map_ax.set_axis_bgcolor(water_fill_color) map_ax.add_feature(ocean, facecolor=water_fill_color) map_ax.add_feature(land, facecolor=continent_fill_color) map_ax.add_feature(borders, edgecolor='0.75') map_ax.coastlines(resolution=resolution, color='0.4') # Draw grid lines - TODO: draw_labels=True doesn't work yet. if projection == 'local': map_ax.gridlines() else: # Draw lat/lon grid lines every 30 degrees. map_ax.gridlines(xlocs=range(-180, 181, 30), ylocs=range(-90, 91, 30)) # Plot labels if labels and len(lons) > 0: with map_ax.hold_limits(): for name, xpt, ypt, _colorpt in zip(labels, lons, lats, color): map_ax.text(xpt, ypt, name, weight="heavy", color="k", zorder=100, transform=ccrs.Geodetic(), path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) scatter = map_ax.scatter(lons, lats, marker=marker, s=size, c=color, zorder=10, cmap=colormap, transform=ccrs.Geodetic()) if title: plt.suptitle(title) # Only show the colorbar for more than one event. if show_colorbar: if colorbar_ticklabel_format is not None: if isinstance(colorbar_ticklabel_format, (str, native_str)): formatter = FormatStrFormatter(colorbar_ticklabel_format) elif hasattr(colorbar_ticklabel_format, '__call__'): formatter = FuncFormatter(colorbar_ticklabel_format) elif isinstance(colorbar_ticklabel_format, Formatter): formatter = colorbar_ticklabel_format locator = MaxNLocator(5) else: if datetimeplot: locator = AutoDateLocator() formatter = AutoDateFormatter(locator) # Compat with old matplotlib versions. if hasattr(formatter, "scaled"): formatter.scaled[1 / (24. * 60.)] = '%H:%M:%S' else: locator = None formatter = None cb = Colorbar(cm_ax, scatter, cmap=colormap, orientation='horizontal', ticks=locator, format=formatter) # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() if show: plt.show() return fig
def test_background_img(): ax = plt.axes(projection=ccrs.Orthographic()) ax.background_img(name='ne_shaded', resolution='low')
def test_LongitudeFormatter_bad_projection(): formatter = LongitudeFormatter() formatter.axis = Mock(axes=Mock(GeoAxes, projection=ccrs.Orthographic())) message = 'This formatter cannot be used with non-rectangular projections.' with assert_raises_regex(TypeError, message): formatter(0)
'PlateCarree': ccrs.PlateCarree(), 'PlateCarree_Dateline': ccrs.PlateCarree(central_longitude=180.0), 'Mollweide_Dateline': ccrs.Mollweide(central_longitude=180.0), 'Mollweide': ccrs.Mollweide(), 'Robinson_Dateline': ccrs.Robinson(central_longitude=180.0), 'Robinson': ccrs.Robinson(), 'SouthPolarStereo': ccrs.SouthPolarStereo(), 'Orthographic': ccrs.Orthographic(central_longitude=240, central_latitude=-45), 'RotatedPole_260E_20N_shift180': ccrs.RotatedPole(260, 20, central_rotated_longitude=180), } line_style_dict = {'dashed': '--', 'solid': '-'} hatch_style_dict = { 'dots': '.', 'fwdlines_wide': '/', 'bwdlines_normal': '\\', 'bwdlines_tight': '\\\\', 'stars': '*' }
def plot_antenna_distribution( source_lon, source_lat, source, antenna, baselines=False, end=False, lon_start=None, lat_start=None, out_path=None, ): x, y, z = source.to_ecef(val=[source_lon, source_lat]) # only use source ? x_enu_ant, y_enu_ant = antenna.to_enu(x, y, z) plt.figure(figsize=(5.78, 3.57), dpi=100) ax = plt.axes(projection=ccrs.Orthographic(source_lon, source_lat)) ax.set_global() ax.coastlines() plt.plot( x_enu_ant, y_enu_ant, marker="o", markersize=3, color="#1f77b4", linestyle="none", label="Antenna positions", ) plt.plot( x, y, marker="*", linestyle="none", color="#ff7f0e", markersize=10, transform=ccrs.Geodetic(), zorder=10, label="Projected source", ) if baselines: plot_baselines(antenna) # projected baselines if end: x_start, y_start, _ = source.to_ecef(val=[lon_start, lat_start]) ax.plot( np.array([x, x_start]), np.array([y, y_start]), marker=".", linestyle="--", color="#d62728", linewidth=1, transform=ccrs.Geodetic(), zorder=10, label="Source path", ) ax.plot( x_start, y_start, marker=".", color="green", zorder=10, label="hi", transform=ccrs.Geodetic(), ) plt.legend( fontsize=9, markerscale=1.5, bbox_to_anchor=(0.95, 1), loc=2, borderaxespad=0.0 ) if out_path is not None: plt.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0.05)
from datetime import datetime import matplotlib.pyplot as plt #import sys; sys.path.append('/media/qliu/Zuoer_dream/mylib') #import pyutil.SMCGrid as smc from SMCPy import SMCGrid as smc # -- 1. important parms debug = 0 genGrid = 0 plotonly = (genGrid == 0) gen_cell_sides = 0 matFnm = 'glb2d.nc' # proj=ccrs.Robinson(central_longitude=0.) # proj=ccrs.PlateCarree(central_longitude=180.) proj = ccrs.Orthographic(central_longitude=180.0, central_latitude=-90) # -- 2. gen grid glbBathy = smc.NCBathy(matFnm, debug=debug) smc.GenSMCGrid(bathy_obj=glbBathy, gen_cell_sides=gen_cell_sides, debug=debug, plotonly=plotonly) # -- 3. Create Grid from file and plot the cells smcFnm = 'GLB2DCell.dat' obsFnm = 'GLB2DObs.dat' glbSMC = smc.UnSMC(smcFnm, dlon=glbBathy.dlon, dlat=glbBathy.dlat, refp=glbBathy.refp) #, proj=proj)
) ds.plot.scatter(x="Te", y="Hm0", c='k', ax=ax, s=2, alpha=0.5) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_xlim(Te_lims) ax.set_ylim(Hm0_lims) fig.savefig(base_name + '_hist2d.pdf') #%% fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()}) ds.plot.scatter( x='spot_lon', y='spot_lat', ax=ax, subplot_kws=dict(projection=ccrs.Orthographic(-80, 35), facecolor="gray"), transform=ccrs.PlateCarree(), label='Spotter', ) ds.plot.scatter( x='wec_lon', y='wec_lat', ax=ax, subplot_kws=dict(projection=ccrs.Orthographic(-80, 35), facecolor="gray"), transform=ccrs.PlateCarree(), label='WEC', ) ax.legend() gl = ax.gridlines( crs=ccrs.PlateCarree(),
def plot_sh_on_sphere(ell, m, args): #ensure valid input assert np.abs(m) <= ell assert np.abs(args.inc) <= 180 outfile = args.outfile if outfile is None: outfile = 'l{0}m{1}_ss{2}.gif'.format(ell, m, '_s' if args.square else '') plotcrs = ccrs.Orthographic(0, 90 - args.inc) #compute spherical harmonic lon = np.linspace(0, 2 * np.pi, args.nlon) - np.pi lat = np.linspace(-np.pi / 2, np.pi / 2, args.nlat) colat = lat + np.pi / 2 d = np.zeros((len(lon), len(colat)), dtype=np.complex64) for j, yy in enumerate(colat): for i, xx in enumerate(lon): d[i, j] = sp.sph_harm(m, ell, xx, yy) # set up figure fig = plt.figure(figsize=(args.size, args.size), tight_layout={'pad': 1}) ax = plt.subplot(projection=plotcrs) if args.square: d = abs(d) vlim = np.max(np.real(d)) # Animate: def animate(i): drm = np.transpose( np.real(d * np.exp(-1.j * (2. * np.pi * float(i) / np.float(args.nframes))))) sys.stdout.write("\rFrame {0} of {1}".format(i + 1, args.nframes)) sys.stdout.flush() ax.clear() ax.pcolormesh(lon * 180 / np.pi, lat * 180 / np.pi, drm, transform=ccrs.PlateCarree(), cmap='seismic', vmin=-vlim if not args.square else 0, vmax=vlim, shading='flat') ax.relim() ax.autoscale_view() def init(): animate(0) if m != 0 and not args.square: interval = args.duration / np.float(args.nframes) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=args.nframes, interval=interval, blit=False) anim.save(outfile, dpi=args.dpi, fps=1. / interval, writer='imagemagick') print('\nWrote ' + outfile) else: # no need for an animation for those parameters animate(0) fig.savefig(outfile.replace('gif', 'png'), dpi=args.dpi) print('\nWrote ' + outfile.replace('gif', 'png'))
This script creates the psyplot icon with a dpi of 128 and a width and height of 8 inches. The file is saved it to ``'icon1024.pkl'``""" import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cf from matplotlib.text import FontProperties # The path to the font fontpath = '/Library/Fonts/FreeSansBoldOblique.ttf' fig = plt.figure(figsize=(8, 8), dpi=128) ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], projection=ccrs.Orthographic(central_latitude=5)) land = ax.add_feature(cf.LAND, facecolor='0.975') ocean = ax.add_feature(cf.OCEAN, facecolor=plt.get_cmap('Blues')(0.5)) text = ax.text(0.47, 0.5, 'Psy', transform=fig.transFigure, name='FreeSans', fontproperties=FontProperties(fname=fontpath), size=256, ha='center', va='center', weight=400)
import numpy as np import scipy.special as sp import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import cartopy.crs as ccrs from specfabpy import specfabpy as sf #------------------ # Plot resolution and options #------------------ inclination = 60 # View angle rot = -90 # View angle prj, geo = ccrs.Orthographic(rot, 90 - inclination), ccrs.Geodetic() latres = 20 lonres = 2 * latres phi = np.linspace(0, 2 * np.pi, lonres) # LON theta = np.linspace(0, np.pi, latres) # CO-LAT phi, theta = np.meshgrid(phi, theta) lon, colat = phi, theta lat = np.pi / 2 - colat lvls = np.linspace(0, 0.4, 6) # Contour levels #------------------ # Plot function #------------------
def test_stock_img(): ax = plt.axes(projection=ccrs.Orthographic()) ax.stock_img()
import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as ccrs air = (xr.tutorial.load_dataset('air_temperature').air.isel(time=0)) ax = plt.axes(projection=ccrs.Orthographic(-80, 35)) ax.set_global() air.plot.contourf(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines() plt.savefig('cartopy_example.png')
def test_pil_Image(): img = Image.open(NATURAL_EARTH_IMG) source_proj = ccrs.PlateCarree() ax = plt.axes(projection=ccrs.Orthographic()) ax.imshow(img, transform=source_proj, extent=[-180, 180, -90, 90])
eof1_norm = (eof1.sel(mode=0) * (-1)) / eof1.sel(mode=0).std() """Daily and monthly AO indices are constructed by projecting the daily and monthly mean 1000-hPa height anomalies onto the leading EOF mode. Both time series are normalized by the standard deviation of the monthly index (1979-2000 base period” - NOAA """ f = f - f.hgt.mean(dim='time') f = f.groupby('time.month') - f.hgt.groupby('time.month').mean() pseudo_pcs_era = ((solver.projectField(f.hgt) * (-1)) / solver.pcs(npcs=1).std()) eof1 = eof1 * (-1) # Plot the leading EOF expressed as covariance in the European/Atlantic domain. clevs = np.linspace(-50, 50, 12) proj = ccrs.Orthographic(0, 90) # ax = plt.axes(projection=proj) plt.figure() ax = plt.subplot(projection=ccrs.Orthographic(0, 90)) ax.coastlines() ax.set_global() eof1.sel(mode=0).plot.pcolormesh(levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree()) ax.set_title('EOF1 expressed as covariance ' + str(round(var1.values * 100, 2)) + '%', fontsize=16) plt.show(block=False) """ ######################################################
def permafrost_area(soiltemp, airtemp, landfrac, run): """Calculate the permafrost area and make a plot.""" # Define parameters of the test to calculate the existence of permafrost thresh_temperature = 273.2 frozen_months = 24 prop_months_frozen = 0.5 # frozen for at least half of the simulation # make a mask of land fraction over non iced areas and extract northern # latitudes nonice = get_nonice_mask(run) mask = iris.analysis.maths.multiply(nonice, landfrac) mask = mask.extract(iris.Constraint(latitude=lambda cell: cell > 0)) # extract northern high latitudes [and deeepst soil level] soiltemp = soiltemp.extract(iris.Constraint(depth=2.0)) # from 1m to 3m # Make an aggregator to define the permafrost extent # I dont really understand this but it works frozen_count = iris.analysis.Aggregator('frozen_count', num_frozen, units_func=lambda units: 1) # Calculate the permafrost locations pf_periods = soiltemp.collapsed('time', frozen_count, threshold=thresh_temperature, frozen_length=frozen_months) tot_time = len(soiltemp.coord('time').points) pf_periods = pf_periods / float(tot_time) pf_periods.rename('Fraction of months layer 4 (-1m to -3m) soil is frozen') # mask out non permafrost points, sea points and ice points pf_periods.data = np.ma.masked_less(pf_periods.data, prop_months_frozen) # set all non-masked values to 1 for area calculation # (may be a better way of doing this but I'm not sure what it is) pf_periods = pf_periods / pf_periods # mask for land area also pf_periods = pf_periods * mask # calculate the area of permafrost # Generate area-weights array. This method requires bounds on lat/lon # coords, add some in sensible locations using the "guess_bounds" # method. for coord in ['latitude', 'longitude']: if not pf_periods.coord(coord).has_bounds(): pf_periods.coord(coord).guess_bounds() grid_areas = iris.analysis.cartography.area_weights(pf_periods) # calculate the areas not masked in pf_periods pf_area = pf_periods.collapsed(['longitude', 'latitude'], iris.analysis.SUM, weights=grid_areas).data # what is the area where the temperature is less than 0 degrees C? airtemp = airtemp.collapsed('time', iris.analysis.MEAN) # if more than 2 dims, select the ground level if airtemp.ndim > 2: airtemp = airtemp[0] airtemp_below_zero = np.where(airtemp.data < 273.2, 1, 0) airtemp_area = np.sum(airtemp_below_zero * grid_areas) pf_prop = pf_area / airtemp_area pf_area = pf_area / 1e12 # Figure Permafrost extent north america plt.figure(figsize=(8, 8)) ax = plt.axes(projection=ccrs.Orthographic(central_longitude=-80.0, central_latitude=60.0)) qplt.pcolormesh(pf_periods) ax.gridlines() ax.coastlines() levels = [thresh_temperature] qplt.contour(airtemp, levels, colors='k', linewidths=3) plt.title('Permafrost extent & zero degree isotherm ({})'.format( run['runid'])) plt.savefig('pf_extent_north_america_' + run['runid'] + '.png') # Figure Permafrost extent asia plt.figure(figsize=(8, 8)) ax = plt.axes(projection=ccrs.Orthographic(central_longitude=100.0, central_latitude=50.0)) qplt.pcolormesh(pf_periods) ax.gridlines() ax.coastlines() levels = [thresh_temperature] qplt.contour(airtemp, levels, colors='k', linewidths=3) plt.title('Permafrost extent & zero degree isotherm ({})'.format( run['runid'])) plt.savefig('pf_extent_asia_' + run['runid'] + '.png') # defining metrics for return up to top level metrics = { 'permafrost area': pf_area, 'fraction area permafrost over zerodeg': pf_prop, } return metrics
filename = example_data_path('hgt_djf.nc') ncin = cdms2.open(filename, 'r') z_djf = ncin('z') ncin.close() # Compute anomalies by removing the time-mean. z_djf_mean = cdutil.averager(z_djf, axis='t') z_djf = z_djf - z_djf_mean z_djf.id = 'z' # Create an EOF solver to do the EOF analysis. Square-root of cosine of # latitude weights are applied before the computation of EOFs. solver = Eof(z_djf, weights='coslat') # Retrieve the leading EOF, expressed as the covariance between the leading PC # time series and the input SLP anomalies at each grid point. eof1 = solver.eofsAsCovariance(neofs=1) # Plot the leading EOF expressed as covariance in the European/Atlantic domain. clevs = np.linspace(-75, 75, 11) lons, lats = eof1.getLongitude()[:], eof1.getLatitude()[:] proj = ccrs.Orthographic(central_longitude=-20, central_latitude=60) ax = plt.axes(projection=proj) ax.set_global() ax.coastlines() ax.contourf(lons, lats, eof1(squeeze=True), levels=clevs, cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree()) plt.title('EOF1 expressed as covariance', fontsize=16) plt.show()
density_bottom = 3000 slope = (density_top - density_bottom) / (top - bottom) return slope * (radius - bottom) + density_bottom # Define computation points on a regular grid at 100km above the mean Earth # radius coordinates = vd.grid_coordinates( region=[-80, -40, -50, -10], shape=(80, 80), extra_coords=100e3 + ellipsoid.mean_radius, ) # Compute the radial component of the acceleration gravity = hm.tesseroid_gravity(coordinates, tesseroids, density, field="g_z") print(gravity) # Plot the gravitational field fig = plt.figure(figsize=(8, 9)) ax = plt.axes(projection=ccrs.Orthographic(central_longitude=-60)) img = ax.pcolormesh(*coordinates[:2], gravity, transform=ccrs.PlateCarree()) plt.colorbar(img, ax=ax, pad=0, aspect=50, orientation="horizontal", label="mGal") ax.coastlines() ax.set_title("Downward component of gravitational acceleration") plt.show()
def plot_data_locs(haarpLoc, radarFnames, ionoFnames, axExtent=[-180, 180, 40, 90]): slant_range = 4000 # Load the radar locations radars = {} for r, fn in radarFnames.items(): radar = nc_utils.load_nc(fn) fovpts = np.ones((len(radar.brng_at_15deg_el), 2)) for ind, brng in enumerate(radar.brng_at_15deg_el): beam_off = brng - radar.boresight fovpts[ind, :] = calcFieldPnt( radar.lat, radar.lon, radar.alt, radar.boresight, beam_off, slant_range, hop=2, adjusted_sr=False, altitude=300, ) radars[r] = { 'lon': radar.lon, 'lat': radar.lat, 'alt': radar.alt, 'fovpts': fovpts, } ionosondes = {} # Load the ionosondes for io, fn in ionoFnames.items(): iono = nc_utils.load_nc(fn) lon = iono.lon if lon > 180: lon -= 360 ionosondes[io] = [iono.lat, lon] # Plot the data locations on a map rp = -130, 55 ax = plt.axes(projection=ccrs.Orthographic(*rp)) data_crs = ccrs.Geodetic() ax.add_feature(cfeature.OCEAN, zorder=0) ax.add_feature(cfeature.LAND, zorder=0, edgecolor='black') ax.add_feature(cfeature.BORDERS, linestyle=':') ax.set_global() # ax.gridlines() # Plot the radars and FOVs for rn, radar in radars.items(): ax.plot(radar['lon'], radar['lat'], marker='.', color='k', markersize=5, transform=data_crs) for ind, brng in enumerate(radar['fovpts'][:, 0]): ax.plot( [radar['lon'], radar['fovpts'][ind, 1]], [radar['lat'], radar['fovpts'][ind, 0]], color='k', transform=data_crs, linewidth=0.3, ) ax.plot(haarpLoc[1], haarpLoc[0], marker='.', color='red', markersize=15, transform=data_crs) # Plot the radar labels geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) for rn, radar in radars.items(): rn = rn.split('.')[0].upper() plt.text(radar['lon'], radar['lat'], rn, verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', boxstyle='round')) # Plot the ionosondes for rn, iono in ionosondes.items(): ax.plot(iono[1], iono[0], marker='.', color='b', markersize=7, transform=data_crs) if rn == 'GAKONA': plt.text(iono[1] + 3, iono[0], 'HAARP', verticalalignment='center', horizontalalignment='left', transform=text_transform, bbox=dict(facecolor='red', boxstyle='round')) elif rn == 'EIELSON': plt.text(iono[1], iono[0], 'Eielson', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='lightblue', boxstyle='round')) elif rn == 'IDAHONATIONALLAB': plt.text(iono[1] + 3, iono[0], 'Idaho National Lab', verticalalignment='center', horizontalalignment='left', transform=text_transform, bbox=dict(facecolor='lightblue', boxstyle='round')) plt.show()
import cartopy.crs as ccrs # co-ordinates taken from Wikipedia article on BiSON 2017-11-20 11:27 coords = { 'Mount Wilson': (34.22, -118.07), 'Las Campanas': (-29.01597, -70.69208), 'Teide Observatory': (28.3, -16.5097), # 'SAAO': (-33.9347, 18.4776), 'Sutherland': (-32.376006, 20.810678), 'Carnarvon': (-24.869167, 113.704722), 'Paul Wild Observatory': (-30.314, 149.562), 'University of Birmingham': (52.450556, -1.930556) } lon0, lat0 = -45, 0 ax = pl.subplot(1, 2, 1, projection=ccrs.Orthographic(lon0, lat0)) # (lon, lat) ax.set_global() ax.add_feature(cartopy.feature.OCEAN, zorder=0) ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black') for lat, lon in coords.values(): if lon0 - 90 < lon < lon0 + 90: pl.plot(lon, lat, 'ro', transform=ccrs.PlateCarree()) lon0, lat0 = 135, 0 ax = pl.subplot(1, 2, 2, projection=ccrs.Orthographic(lon0, lat0)) # (lon, lat) ax.set_global() ax.add_feature(cartopy.feature.OCEAN, zorder=0) ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black')
def plot_radars(radars, radarFnames, time, haarpLat, haarpLon, outFname=None): rp = -130, 55 transform = ccrs.Geodetic() ax = plt.axes(projection=ccrs.Orthographic(*rp)) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS, linestyle=':') gl = ax.gridlines( crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.5, color='gray', linestyle='-', ) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER style = {'size': 10, 'color': 'gray'} gl.xlabel_style = style gl.ylabel_style = style gl.top_labels = False gl.right_labels = False ax.set_global() for radar, rg_b in radars.items(): inFname = radarFnames[radar] print('plotting %s' % inFname) bm = rg_b[1] rg = rg_b[0] data = nc_utils.ncread_vars(inFname) rgi = (data['range'] > rg[0]) & (data['range'] < rg[1]) for k, v in data.items(): data[k] = v[rgi] if 'kod' in radar: data['v'][:] = -1000 else: data['v'][:] = 1000 hdr = nc_utils.load_nc(inFname) ax.plot( hdr.lon, hdr.lat, color="k", marker="o", transform=transform, ) ax = plot_radar( ax, data, hdr.lat, hdr.lon, time, ) ax.plot(haarpLon, haarpLat, marker='o', color='red', transform=transform) # Plot the radar labels geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) for rn, radar in radars.items(): rn = rn.split('.')[0].upper() plt.text(radar['lon'], radar['lat'], rn, verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', boxstyle='round')) ax.xaxis.zoom(3) ax.yaxis.zoom(3) plt.suptitle(time.strftime('%Y %b %d %H:%M')) if outFname: plt.savefig(outFname) print('Saved to %s' % outFname) else: plt.show() plt.close()
fixed_plate) lat, lon, angle = rotation.get_lat_lon_euler_pole_and_angle_degrees() euler_pole = mcplates.EulerPole(lon, lat, 1.) # Don't care about the rate here pole.rotate(euler_pole, -angle) lats[i] = pole.latitude lons[i] = pole.longitude average_rotation = rotation_model.get_rotation(times[-1], australia, 0.0, fixed_plate) print average_rotation.get_lat_lon_euler_pole_and_angle_degrees() mlats = [muller_apw(t)[1] for t in times] mlons = [muller_apw(t)[0] for t in times] ax = plt.axes(projection=ccrs.Orthographic(120., -30.)) ax.plot(lons, lats, transform=ccrs.PlateCarree(), lw=2) ax.plot(mlons, mlats, transform=ccrs.PlateCarree(), lw=2) ax.set_global() ax.gridlines() lon_shift = 0. mcplates.plot.plot_continent(ax, 'australia', rotation_pole=mcplates.Pole(0., 90., 1.0), angle=-lon_shift, color='k') mcplates.plot.plot_continent(ax, 'antarctica', rotation_pole=mcplates.Pole(0., 90., 1.0), angle=-lon_shift, color='k')
def plotray2D(ray_datenum, raylist, ray_out_dir, crs, carsph, units, md, t_save=None, show_plot=True, plot_density=False, damping_vals=None): # !!!!!!! ONLY suports cartesian plotting! # first, find the max index of refraction if plot_density is selected for weighting purposes if plot_density: r = raylist[0] # just grab the first ray w = r['w'] # call stix parameters to find resonance cone R, L, P, S, D = stix_parameters(r, 0, w) resangle = np.arctan(np.sqrt(-P / S)) root = -1 # whistler solution # Solve the cold plasma dispersion relation # subtract 3 to avoid infinity index of refr. and match the initialization at bfield script cos2phi = pow(np.cos(resangle - (3 * D2R)), 2) sin2phi = pow(np.sin(resangle - (3 * D2R)), 2) A = S * sin2phi + P * cos2phi B = R * L * sin2phi + P * S * (1.0 + cos2phi) discriminant = B * B - 4.0 * A * R * L * P n1sq = (B + np.sqrt(discriminant)) / (2.0 * A) n2sq = (B - np.sqrt(discriminant)) / (2.0 * A) # negative refers to the fact that ^^^ B - sqrt #n1 = np.sqrt(n1sq) if n2sq < 0: n2 = np.sqrt(n2sq * -1) else: n2 = np.sqrt(n2sq) nmax = n2 # initialize for next step weights = [] # convert to desired coordinate system into vector list rays ray_coords = [] ray_count = 0 for r in raylist: ray_count += 1 w = r['w'] # comes in as SM car in m tmp_coords = list(zip(r['pos'].x, r['pos'].y, r['pos'].z)) nmag = np.sqrt(r['n'].x.iloc[0]**2 + r['n'].y.iloc[0]**2 + r['n'].z.iloc[0]**2) tvec_datetime = [ ray_datenum + dt.timedelta(seconds=s) for s in r['time'] ] new_coords = convert2(tmp_coords, tvec_datetime, 'SM', 'car', ['m', 'm', 'm'], crs, carsph, units) # save it ray_coords.append(new_coords) if plot_density: # save weighting factor, constant along path the_weight = nmag / nmax if damping_vals: ray_damp = np.ones(len(new_coords)) time_array = damping_vals[0] all_damp = damping_vals[1] for rt, tt in enumerate(r['time']): for ti, ta in enumerate(time_array): if np.abs(tt - ta ) < 1e-2: # find which time point is closest ray_damp[rt] = all_damp[ti] weights.append(ray_damp * the_weight) else: weights.append(np.ones(len(new_coords)) * the_weight) # -------------------------------- PLOTTING -------------------------------- ray1 = ray_coords[0][0] ray1_sph = convert2([ray1], tvec_datetime, crs, carsph, units, 'GEO', 'sph', ['m', 'deg', 'deg']) # find ray starting long long = ray1_sph[0][2] # convert for cartopy issues if long > 180: plane_long = 180 - (long - 180) catch = -1 else: plane_long = long catch = 1 try: import cartopy import cartopy.crs as ccrs # make this into a an image (sneaky) ax = plt.axes(projection=ccrs.Orthographic( central_longitude=(catch * plane_long) - 90, central_latitude=0.0)) ax.add_feature(cartopy.feature.OCEAN, zorder=0) ax.add_feature(cartopy.feature.LAND, zorder=0, edgecolor='black') ax.coastlines() plt.savefig(ray_out_dir + '/ccrs_proj.png') plt.cla() import matplotlib.patches as patches import matplotlib.cbook as cbook img = plt.imread(ray_out_dir + '/ccrs_proj.png', format='png') fig, ax = plt.subplots(figsize=(6, 6)) im = ax.imshow(img, extent=[-1.62, 1.62, -1.3, 1.3], zorder=2) # not the most scientific patch = patches.Circle((0, 0), radius=1.02, transform=ax.transData) im.set_clip_path(patch) except: fig, ax = plt.subplots(figsize=(6, 6)) earth = plt.Circle((0, 0), 1, color='b', alpha=0.5, zorder=100) iono = plt.Circle((0, 0), (R_E + H_IONO) / R_E, color='g', alpha=0.5, zorder=99) ax.add_artist(earth) ax.add_artist(iono) # plot the rays rotated_rcoords = [] for rayc in ray_coords: for rc in rayc: rotated = rotateplane([rc], tvec_datetime, crs, carsph, units) rotated_rcoords.append(rotated[0]) # repack in xz plane rotated_rcoords_x = [rcs[0] for rcs in rotated_rcoords] rotated_rcoords_z = [rcs[2] for rcs in rotated_rcoords] if plot_density: # clean up weights list weights = [item for sublist in weights for item in sublist] binnum = 40 binlon = np.linspace(0, 4, num=binnum) binlat = np.linspace(-2, 2, num=binnum) cmap = plt.cm.get_cmap('Blues') # create the density plot # log norm scale nrays = 10000 h = ax.hist2d(rotated_rcoords_x, rotated_rcoords_z, bins=[np.array(binlon), np.array(binlat)], weights=weights, norm=mpl.colors.LogNorm(), cmap=cmap) ticks = [1, 10, 100, 1000, 1e4] tlabels = [10 * np.log10(i / nrays) for i in ticks] cbar = fig.colorbar(h[3], ax=ax, shrink=0.84, pad=0.02, ticks=ticks) cbar.set_label(label='dBW', weight='bold') cbar.ax.set_yticklabels([str(int(tt)) for tt in tlabels ]) # vertically oriented colorbar else: # or just plot the ray paths ax.scatter(rotated_rcoords_x[0], rotated_rcoords_z[0], c='Blue', s=10) ax.scatter(rotated_rcoords_x, rotated_rcoords_z, c='Black', s=1, zorder=103) if t_save: ax.scatter(rotated_rcoords_x[t_save], rotated_rcoords_z[t_save], c='r', s=20, zorder=104) # set as dummy variable for return nmax = 1 # final clean up # plot field lines (from IGRF13 model) L_shells = [2, 3, 4] # Field lines to draw Lshell_flines = get_Lshells(L_shells, tvec_datetime, crs, carsph, units) for lfline in Lshell_flines: ax.plot(lfline[0], lfline[1], color='Black', linewidth=1, linestyle='dashed') plt.xlabel('L (R$_E$)') plt.ylabel('L (R$_E$)') #plt.xlim([0, max(L_shells)]) plt.xlim([0, 3]) plt.ylim([-2, 2]) if t_save: plt.savefig(ray_out_dir + '/' + dt.datetime.strftime(ray_datenum, '%Y_%m_%d_%H%M%S') + '_' + str(round(w / (1e3 * np.pi * 2), 1)) + 'kHz' + '_2Dview' + str(md) + '_' + str(t_save) + '.png') else: plt.title( dt.datetime.strftime(ray_datenum, '%Y-%m-%d %H:%M:%S') + ' ' + str(round(w / (1e3 * np.pi * 2), 1)) + 'kHz') plt.savefig(ray_out_dir + '/' + dt.datetime.strftime(ray_datenum, '%Y_%m_%d_%H%M%S') + '_' + str(round(w / (1e3 * np.pi * 2), 1)) + 'kHz' + '_2Dview' + str(md) + '.png') if show_plot: plt.show() plt.close() return nmax
calculate normal gravity at any latitude and height (it's symmetric in the longitudinal direction). The ellipsoid in the calculations used can be changed using :func:`harmonica.set_ellipsoid`. """ import matplotlib.pyplot as plt import cartopy.crs as ccrs import harmonica as hm import verde as vd # Create a global computation grid with 1 degree spacing region = [0, 360, -90, 90] longitude, latitude = vd.grid_coordinates(region, spacing=1) # Compute normal gravity for the WGS84 ellipsoid (the default) on its surface gamma = hm.normal_gravity(latitude=latitude, height=0) # Make a plot of the normal gravity using Cartopy plt.figure(figsize=(10, 10)) ax = plt.axes(projection=ccrs.Orthographic()) ax.set_title("Normal gravity of the WGS84 ellipsoid") ax.coastlines() pc = ax.pcolormesh(longitude, latitude, gamma, transform=ccrs.PlateCarree()) plt.colorbar(pc, label="mGal", orientation="horizontal", aspect=50, pad=0.01, shrink=0.5) plt.tight_layout() plt.show()
if __name__ == '__main__': """ Check the RISR and SD overlap """ plot_out = "save" rkn_lon, rkn_lat = -92.113, 62.82 # RKN inv_lon, inv_lat = -133.77, 68.41 # INV risr_lon, risr_lat = -94.91, 74.73 # RISR fig = plt.figure(figsize=(8, 5), dpi=300) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Orthographic(rkn_lon, rkn_lat)) # ax.set_global() ax.set_extent([-37, -143, 35, 90]) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.LAND) # ax.stock_img() # ax.add_feature(cfeature.COASTLINE) # ax.add_feature(cfeature.BORDERS, linestyle="-", linewidth=0.5) radar_marker_size = 4 # Add RKN to the map plt.plot([rkn_lon, rkn_lon], [rkn_lat, rkn_lat], 'go', markersize=radar_marker_size, transform=ccrs.Geodetic(), label="RKN")
from matplotlib.animation import FFMpegWriter logger = logging.getLogger(__name__) # Parameters first_frame = 1 #last_frame = 8 figsize = (3, 3) dpi = 300 show_time = True gridlines = True coastlines = False edgecolor = 'k' proj = ccrs.PlateCarree(central_longitude=0) #, central_latitude=30) proj = ccrs.Mollweide(central_longitude=0) proj = ccrs.Orthographic(central_longitude=0, central_latitude=30) #fields = ['p','om','vth','vph'] #fields = ['v_ph', 'om'] fields = ['om', 'v_ph'] sim_number = 1 #set as the suffix of the video file input_folder = 'output' #input folder for data output_folder = 'videos' #where to write the video? FPS = 15 step = 3 #data frames to skip per video frame if not os.path.exists(output_folder): os.mkdir(output_folder) #count files in the input folder last_frame = len(glob.glob1("".join([input_folder, '/']), "*.npz")) logger.info('Total number of frames: %i' % (last_frame))
def plot_CONUS(mme_diff, cmap_name=plt.cm.BrBG, vmax=None, vmin=None): lono = mme_diff.getLongitude()[:] lato = mme_diff.getLatitude()[:] lon, lat = np.meshgrid(lono, lato) states_provinces = cfeature.NaturalEarthFeature(category='cultural',\ name='admin_1_states_provinces_lines',\ scale='50m',\ facecolor='none') extent_lonlat = (-125, -70, 22, 50) #clevs = np.array([-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,.3,.4,.5,.6])*2.5 if vmin is None: vmin = np.percentile(mme_diff.compressed(), 5) if vmax is None: vmax = np.percentile(mme_diff.compressed(), 95) clevs = np.linspace(vmin, vmax, 13) clevs_units = clevs.copy() nmap = plt.cm.get_cmap(name=cmap_name, lut=clevs.size - 1) ocean_color = np.float64([209, 230, 241]) / 255 fig = plt.figure(figsize=(12, 12), facecolor="white") ax = fig.add_subplot(1, 1, 1, projection=ccrs.Orthographic(central_longitude=-100, central_latitude=25, globe=None)) m = ax.contourf(lon, lat, mme_diff, clevs, transform=ccrs.PlateCarree(), cmap=nmap, extend="both") ax.coastlines() ax.set_global() ax.set_extent(extent_lonlat, crs=ccrs.PlateCarree()) #ax.gridlines(xlocs=np.arange(-180,190,10),ylocs=np.arange(-180,190,10)) ax.add_feature(cfeature.BORDERS, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(states_provinces, linewidth=0.5, linestyle='-', edgecolor='k') #ax.add_feature(newcoast, linewidth=0.5, linestyle='-', edgecolor='k') #ax.add_feature(newlake, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(cartopy.feature.LAND, color='w', zorder=0, edgecolor='k') ax.add_feature(cartopy.feature.OCEAN, color=ocean_color, zorder=0, edgecolor='k') ax.add_feature(cfeature.BORDERS, linewidth=0.5, linestyle='-', edgecolor='k') ax.add_feature(cartopy.feature.OCEAN, color=ocean_color, zorder=1) #ax.add_feature(newcoast, linewidth=1, linestyle='-', zorder=2,edgecolor='k') #ax.text(-122,21,var_txt+' ('+seas_txt+')',transform=ccrs.PlateCarree(),fontsize=32,fontweight="bold", \ #horizontalalignment='center', verticalalignment='center',) #ax.text(-122,17,ssp_txt,transform=ccrs.PlateCarree(),fontsize=28,fontweight="normal", \ #horizontalalignment='center', verticalalignment='center',) cbar = plt.colorbar(m, orientation="horizontal", fraction=0.08, pad=0.04, ticks=clevs_units[np.arange(0, clevs_units.size + 1, 2)]) cbar.ax.tick_params(labelsize=24)