Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
plt.show()
########################################################################################
# We can estimate the polynomial coefficients for this trend:
trend = vd.Trend(degree=1).fit(coordinates, data.air_temperature_c)
print(trend.coef_)
########################################################################################
# More importantly, we can predict the trend values and remove them from our data:
trend_values = trend.predict(coordinates)
residuals = data.air_temperature_c - trend_values
fig, axes = plt.subplots(
1, 2, figsize=(10, 6), subplot_kw=dict(projection=ccrs.Mercator())
)
ax = axes[0]
ax.set_title("Trend")
tmp = ax.scatter(
data.longitude,
data.latitude,
c=trend_values,
s=60,
cmap="plasma",
transform=ccrs.PlateCarree(),
)
plt.colorbar(tmp, ax=ax, orientation="horizontal", pad=0.06)
vd.datasets.setup_texas_wind_map(ax)
ax = axes[1]
# add embelishments
if embelish is True:
# Create a feature for States/Admin 1 regions at 1:resolution
# from Natural Earth
states_provinces = cartopy.feature.NaturalEarthFeature(
category='cultural',
name='admin_1_states_provinces_lines',
scale=resolution,
facecolor='none')
ax.coastlines(resolution=resolution)
ax.add_feature(states_provinces, edgecolor='gray')
# labeling gridlines poses some difficulties depending on the
# projection, so we need some projection-spectific methods
if ax.projection in [cartopy.crs.PlateCarree(),
cartopy.crs.Mercator()]:
gl = ax.gridlines(xlocs=lon_lines, ylocs=lat_lines,
draw_labels=True)
gl.xlabels_top = False
gl.ylabels_right = False
elif isinstance(ax.projection, cartopy.crs.LambertConformal):
fig.canvas.draw()
ax.gridlines(xlocs=lon_lines, ylocs=lat_lines)
# Label the end-points of the gridlines using the custom
# tick makers:
ax.xaxis.set_major_formatter(
cartopy.mpl.gridliner.LONGITUDE_FORMATTER)
ax.yaxis.set_major_formatter(
cartopy.mpl.gridliner.LATITUDE_FORMATTER)
if _LAMBERT_GRIDLINES:
If the file isn't already in your data directory, it will be downloaded
automatically.
"""
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import verde as vd
import harmonica as hm
import numpy as np
# Fetch the data in a pandas.DataFrame
data = hm.datasets.fetch_britain_magnetic()
print(data)
# Plot the observations in a Mercator map using Cartopy
fig = plt.figure(figsize=(7.5, 10))
ax = plt.axes(projection=ccrs.Mercator())
ax.set_title("Magnetic data from Great Britain", pad=25)
maxabs = np.percentile(data.total_field_anomaly_nt, 99)
tmp = ax.scatter(
data.longitude,
data.latitude,
c=data.total_field_anomaly_nt,
s=0.001,
cmap="seismic",
vmin=-maxabs,
vmax=maxabs,
transform=ccrs.PlateCarree(),
)
plt.colorbar(
tmp,
ax=ax,
label="total field magnetic anomaly [nT]",
##############
self.update_datalim(corners)
self.add_collection(collection)
self.autoscale_view()
########################
# PATCH
# XXX Non-standard matplotlib thing.
# Handle a possible wrap around for rectangular projections.
t = kwargs.get('transform', None)
if isinstance(t, ccrs.CRS):
wrap_proj_types = (ccrs._RectangularProjection,
ccrs._WarpedRectangularProjection,
ccrs.InterruptedGoodeHomolosine,
ccrs.Mercator)
if isinstance(t, wrap_proj_types) and \
isinstance(self.projection, wrap_proj_types):
C = C.reshape((Ny - 1, Nx - 1))
transformed_pts = transformed_pts.reshape((Ny, Nx, 2))
# Compute the length of edges in transformed coordinates
with np.errstate(invalid='ignore'):
edge_lengths = np.hypot(
np.diff(transformed_pts[..., 0], axis=1),
np.diff(transformed_pts[..., 1], axis=1)
)
to_mask = (
(edge_lengths > abs(self.projection.x_limits[1] -
self.projection.x_limits[0]) / 2) |
np.isnan(edge_lengths)
"""
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import rockhound as rh
# The data are in a pandas.DataFrame
data = rh.fetch_texas_wind()
print(data.head())
# Make a Mercator map of the data using Cartopy
plt.figure(figsize=(8, 6))
ax = plt.axes(projection=ccrs.Mercator())
ax.set_title("Wind speed and air temperature for Texas")
# Plot the air temperature as colored circles and the wind speed as vectors.
plt.scatter(
data.longitude,
data.latitude,
c=data.air_temperature_c,
s=100,
cmap="plasma",
transform=ccrs.PlateCarree(),
)
plt.colorbar().set_label("Air temperature (C)")
ax.quiver(
data.longitude.values,
data.latitude.values,
data.wind_speed_east_knots.values,
data.wind_speed_north_knots.values,
mexample = mbasemap.Basemap(projection=projection, **projection_kwargs)
# Override aspect ratio
aspect = (mexample.urcrnrx-mexample.llcrnrx)/(mexample.urcrnry-mexample.llcrnry)
if not silent: print(f"Forcing aspect ratio: {aspect:.3g}")
# Cartopy stuff; get crs instance, and create dictionary to add to add_subplot calls
cartopy_kwargs = {}
if maps and package=='cartopy':
# Get the projection instance from a string and determine the
# correct aspect ratio (TODO) also prevent auto-scaling
projection = projection or 'cyl'
crs_dict = {
**{key: ccrs.PlateCarree for key in ('cyl','rectilinear','pcarree','platecarree')},
**{key: ccrs.Mollweide for key in ('moll','mollweide')},
**{key: ccrs.Stereographic for key in ('stereo','stereographic')},
'mercator': ccrs.Mercator,
'robinson': ccrs.Robinson,
'ortho': ccrs.Orthographic,
'aeqd': ccrs.AzimuthalEquidistant,
'aeqa': ccrs.LambertAzimuthalEqualArea,
'wintri': WinkelTripel,
'hammer': Hammer,
'aitoff': Aitoff,
'kav7': KavrayskiyVII,
}
crs_translate = { # less verbose keywords, actually match proj4 keywords and similar to basemap
'lat0': 'central_latitude',
'lat_0': 'central_latitude',
'lon0': 'central_longitude',
'lon_0': 'central_longitude',
}
postprocess_keys = ('latmin', 'lat_min', 'threshold') # will be processed down the line
import projection
from projection import *
reload(projection)
from projection import *
ADDE_HOST = "adde.ucar.edu"
DEGREES_TO_RADIANS = np.pi/180.
# projections coming back from ADDE
MERC = 0x4D455243
TANC = 0x54414E43
projections = {MERC : (Mercator, ccrs.Mercator), \
TANC : (Tangent_Cone, ccrs.LambertConformal)}
class mysocket:
'''Socket class'''
def __init__(self, sock=None):
'''Initialize the socket'''
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
'''Socket connection, given a host and port'''
self.sock.connect((host, port))
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import numpy as np
import rockhound as rh
# The data are in a pandas.DataFrame
data = rh.fetch_california_gps()
print(data.head())
# Make a plot of the data using Cartopy to handle projections and coastlines
crs = ccrs.PlateCarree()
fig, axes = plt.subplots(
1, 2, figsize=(8, 4), subplot_kw=dict(projection=ccrs.Mercator())
)
# Plot the horizontal velocity vectors
ax = axes[0]
ax.set_title("GPS horizontal velocities")
ax.quiver(
data.longitude.values,
data.latitude.values,
data.velocity_east.values,
data.velocity_north.values,
scale=0.3,
transform=crs,
)
# Plot the vertical velocity
ax = axes[1]
ax.set_title("Vertical velocity")
maxabs = np.abs(data.velocity_up).max()
(data.longitude, data.latitude),
maxdist=spacing * 2 * 111e3,
coordinates=coordinates,
projection=pyproj.Proj(proj="merc", lat_ts=data.latitude.mean()),
)
print(mask)
# Create a dummy grid with ones that we can mask to show the results.
# Turn points that are too far into NaNs so they won't show up in our plot.
dummy_data = np.ones_like(coordinates[0])
dummy_data[~mask] = np.nan
# Make a plot of the masked data and the data locations.
crs = ccrs.PlateCarree()
plt.figure(figsize=(7, 6))
ax = plt.axes(projection=ccrs.Mercator())
ax.set_title("Only keep grid points that are close to data")
ax.plot(data.longitude, data.latitude, ".y", markersize=0.5, transform=crs)
ax.pcolormesh(*coordinates, dummy_data, transform=crs)
vd.datasets.setup_baja_bathymetry_map(ax, land=None)
plt.tight_layout()
plt.show()
def main():
# URL of NASA GIBS
URL = 'https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi'
wmts = WebMapTileService(URL)
# Layers for MODIS true color and snow RGB
layers = ['MODIS_Terra_SurfaceReflectance_Bands143',
'MODIS_Terra_CorrectedReflectance_Bands367']
date_str = '2016-02-05'
# Plot setup
plot_CRS = ccrs.Mercator()
geodetic_CRS = ccrs.Geodetic()
x0, y0 = plot_CRS.transform_point(4.6, 43.1, geodetic_CRS)
x1, y1 = plot_CRS.transform_point(11.0, 47.4, geodetic_CRS)
ysize = 8
xsize = 2 * ysize * (x1 - x0) / (y1 - y0)
fig = plt.figure(figsize=(xsize, ysize), dpi=100)
for layer, offset in zip(layers, [0, 0.5]):
ax = fig.add_axes([offset, 0, 0.5, 1], projection=plot_CRS)
ax.set_xlim((x0, x1))
ax.set_ylim((y0, y1))
ax.add_wmts(wmts, layer, wmts_kwargs={'time': date_str})
txt = ax.text(4.7, 43.2, wmts[layer].title, fontsize=18, color='wheat',
transform=geodetic_CRS)
txt.set_path_effects([PathEffects.withStroke(linewidth=5,
foreground='black')])