def main(): # Create a Stamen Terrain instance. terrain = cimgt.StamenTerrain() # Create a GeoAxes in the tile's projection. plt.figure(figsize=(10,10)) ax = plt.axes(projection=terrain.crs) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([-122.3, -122, 46.1, 46.3]) # Add the MapQuest data at zoom level 8. ax.add_image(terrain, 12) # Add a marker for the Mount Saint Helens volcano. plt.plot(-122.189611,46.205868, marker='o', color='yellow', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. plt.text(-122.189611,46.205868, u'Mount Saint Helens Volcano', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='wheat', alpha=0.5, boxstyle='round')) gl=ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False plt.show()
def try_make_plots_from_cubes(cube, save_filepath, figsize=(16,9), terrain=cimgt.StamenTerrain(), logscaled=True, vmin=None, vmax=None, colourmap='viridis', colourbarticks=None, colourbarticklabels=None, colourbar_label=None, markerpoint=None, markercolor='#B9DC0C', timestamp=None, time_box_position=None, plottitle=None, box_colour='#FFFFFF', textcolour=None, coastlines=False): """" Makes sample plot from cube. Can be used to refine plot specifications. Args: cube_list: Takes a cube. save_filepath: Filepath where the plot will be saved. Kwargs: figsize: Sets size of figure. Default is 16 in x 9 in. Takes a tuple of integers or floats (e.g. (16, 9)). terrain: Sets background map image on plot. Default is Stamen Terrain. See further options here: https://scitools.org.uk/cartopy/docs/latest/cartopy/io/img_tiles.html logscaled: Plots data on a logarithmic (to the base-10) scale. Takes True or False. Makes more appealing visualisations of skewed data. Default is True. vmin: set lowest value to be displayed. Takes a float. vmax: set highest value to be displayed. Takes a float. colourmap: Sets colour map for the plot. Default is 'viridis'. Other colourmaps: 'magma', 'plasma', 'inferno', 'cividis'. See https://matplotlib.org/tutorials/colors/colormaps.html for more colourmap options. colourbarticks: Sets position within data of ticks on colourbar. Takes a list of floats or integers, e.g. [10, 100, 1000]. colourbarticklabels: Sets labels for colourbar ticks. Takes a list, eg. [10, 100, 1000]. colourbar_label: Sets colourbar legend. Takes a string. markerpoint: Plots a marker on the map based on global coordinates. Takes a tuple in this format - (longitude, latitude, 'name_of_place'), longitude and latitude must be a float, name_of_place must be a string. markercolor: Color of the location marker. Must be given as a string. Default is '#B9DC0C'. timestamp: Places a timestamp box on each plot. Takes a string referring to name of timestep metadata within the cube. It must contain timesteps in original metadata to use this, as this takes the name of the timestep attribute. plottitle: Displays the title of your video horizontally across the top of the plots. Takes a string. time_box_position: Position of timestamp box on the plot. Takes a tuple of integers eg. (60, 0) box_colour: Sets colour of title box and colourbar label box. Takes a string. textcolor: Sets colour of text within boxes. Takes a string. coastlines: Draw coastlines around land on the map. Takes True or False. """ cube_list = cube __make_plots_from_cubes__(cube_list)
def main(): # Create a Stamen Terrain instance. stamen_terrain = cimgt.StamenTerrain() fig = plt.figure() # Create a GeoAxes in the tile's projection. ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs) # Limit the extent of the map to a small longitude/latitude range. ax.set_extent([-22, -15, 63, 65], crs=ccrs.Geodetic()) # Add the Stamen data at zoom level 8. ax.add_image(stamen_terrain, 8) # Add a marker for the Eyjafjallajökull volcano. ax.plot(-19.613333, 63.62, marker='o', color='red', markersize=12, alpha=0.7, transform=ccrs.Geodetic()) # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add text 25 pixels to the left of the volcano. ax.text(-19.613333, 63.62, u'Eyjafjallajökull', verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round')) plt.show()
def plot_on_map(df, x_col_name, y_col_name, sub_n=None, sub_m=None, sub_i=None): ''' Plot data on map ''' if sub_n is None or sub_m is None or sub_i is None: plt.figure(figsize=(10, 10)) sub_n = 1 sub_m = 1 sub_i = 1 minLat = min(df[y_col_name]) minLon = min(df[x_col_name]) maxLat = max(df[y_col_name]) maxLon = max(df[x_col_name]) # create a Stamen Terrain instance. stamen_terrain = cimgt.StamenTerrain() # create a GeoAxes in the tile's projection. ax = plt.subplot(sub_n, sub_m, sub_i, projection=stamen_terrain.crs) # limit the extent of the map to a small longitude/latitude range. ax.set_extent([minLon, maxLon, minLat, maxLat]) quality = 14 ax.add_image(stamen_terrain, quality) ax.plot(df[x_col_name], df[y_col_name], 'r.', transform=ccrs.Geodetic(), markersize=6) return ax
import pandas as pd from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature demands = pd.read_csv('../Summary_info/demands.csv', index_col=0) structures = pd.read_csv('../Structures_files/modeled_diversions.csv', index_col=0) for index, row in structures.iterrows(): structures.at[str(index), 'Mean demand'] = np.mean(demands.loc[str(index)].values) extent = [-109.069, -105.6, 38.85, 40.50] extent_large = [-111.0, -101.0, 36.5, 41.5] #rivers_10m = cpf.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '10m') tiles = cimgt.StamenTerrain(style='terrain') shape_feature = ShapelyFeature( Reader('../Structures_files/Shapefiles/Water_Districts.shp').geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='None') flow_feature = ShapelyFeature( Reader('../Structures_files/Shapefiles/UCRBstreams.shp').geometries(), ccrs.PlateCarree(), edgecolor='royalblue', facecolor='None') fig = plt.figure(figsize=(18, 9)) ax = plt.axes(projection=tiles.crs) #ax.add_feature(rivers_10m, facecolor='None', edgecolor='royalblue', linewidth=2, zorder=4) ax.add_image(tiles, 9, interpolation='none', alpha=0.8)
def plot_map(self): """Plot the PGA map.""" stamen_terrain = cimgt.StamenTerrain() geodetic_transform = ccrs.PlateCarree() # Create a GeoAxes fig, ax = plt.subplots(1, figsize=(10, 10), subplot_kw={'projection': geodetic_transform}) extent = (self.lon0, self.lon1, self.lat0, self.lat1) ax.set_extent(extent) ax.add_image(stamen_terrain, 11) # ax.coastlines('10m') ax.gridlines(draw_labels=True, color='#777777', linestyle='--') self._plot_circles(ax) norm, cmap, bounds = self._colormap() unknown_soils = False cmp_ids = self._select_stations_pga() texts = [] markers = [] for n, cmp_id in enumerate(cmp_ids): cmp_attrib = self.attributes[cmp_id] lon = cmp_attrib['longitude'] lat = cmp_attrib['latitude'] pga = cmp_attrib['pga'] marker = '^' if self.conf['soil_conditions']: soil_cnd = cmp_attrib['soil_cnd'] if soil_cnd == 'U': unknown_soils = True marker = self.markers[soil_cnd] m, = ax.plot(lon, lat, marker=marker, markersize=12, markeredgewidth=1, markeredgecolor='k', color=cmap(norm(pga)), transform=geodetic_transform, zorder=10) markers.append(m) stname = cmp_id.split('.')[1] t = ax.text(lon, lat, stname, size=8, weight='bold', zorder=99) t.set_path_effects([ path_effects.Stroke(linewidth=1.5, foreground='white'), path_effects.Normal() ]) texts.append(t) if self.conf['soil_conditions']: kwargs = { 'markersize': 8, 'markeredgewidth': 1, 'markeredgecolor': 'k', 'color': '#cccccc', 'linewidth': 0, 'transform': geodetic_transform } rock_station, = ax.plot(-self.lon0, -self.lat0, marker=self.markers['R'], label='rock', **kwargs) soil_station, = ax.plot(-self.lon0, -self.lat0, marker=self.markers['S'], label='soil', **kwargs) handles = [rock_station, soil_station] if unknown_soils: unk_station, = ax.plot(-self.lon0, -self.lat0, marker=self.markers['U'], label='unknown', **kwargs) handles.append(unk_station) legend = ax.legend(handles=handles, loc=self.legend_loc) legend.set_zorder(99) # Add a colorbar ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes('right', size='100%', pad='-30%', aspect=15., map_projection=stamen_terrain.crs) cax.background_patch.set_visible(False) cax.outline_patch.set_visible(False) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) if self.colorbar_bcsf: fig.colorbar(sm, extend='max', ticks=bounds, cax=cax) else: fig.colorbar(sm, extend='max', cax=cax) cax.get_yaxis().set_visible(True) cax.set_ylabel('PGA (mg)') adjust_text(texts, add_objects=markers) outfile = self.basename + '_pga_map_fig.png' fig.savefig(outfile, dpi=300, bbox_inches='tight')
def make_map(projection=ccrs.PlateCarree()): fig, ax = plt.subplots(figsize=(9, 13), subplot_kw=dict(projection=projection)) gl = ax.gridlines(draw_labels=False) gl.xlabels_top = gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER return fig, ax # In[19]: extent = [-122.75, -122.35, 38.0, 38.4] # request = cimgt.GoogleTiles() request = cimgt.StamenTerrain() # request = cimgt.Image() # request = cimgt.OSM() fig, ax = make_map(projection=ccrs.epsg(2871)) ax.set_extent(extent) ax.add_image(request, 10) modelmap = flopy.plot.ModelMap(model=fb, ax=ax) modelmap.plot_array(head, ax=ax, transform=ccrs.epsg(2871)) modelmap.contour_array(head, levels=np.arange(-50, 500, 25), ax=ax) # modelmap.plot_ibound(ax = ax) modelmap.plot_inactive() # In[ ]:
def plot_flopy_par_ensemble_test(): import shutil import numpy as np try: import flopy except: return try: import matplotlib.pyplot as plt except: print("error importing pyplot") return import pyemu org_model_ws = os.path.join("..", "examples", "Freyberg_transient") nam_file = "freyberg.nam" new_model_ws = "temp_pst_from_flopy" pp_props = [["upw.hk", 0], ["upw.hk", 1]] helper = pyemu.helpers.PstFromFlopyModel(nam_file, new_model_ws, org_model_ws, grid_props=pp_props, remove_existing=True, model_exe_name="mfnwt") pst = pyemu.Pst(os.path.join(new_model_ws,"freyberg.pst")) mc = pyemu.MonteCarlo(pst=pst) os.chdir(new_model_ws) cov = pyemu.Cov.from_ascii("freyberg.pst.prior.cov") mc.draw(100,cov=cov) #pyemu.helpers.plot_flopy_par_ensemble(mc.pst, mc.parensemble, num_reals=None, model=helper.m) #pyemu.helpers.plot_flopy_par_ensemble(mc.pst, mc.parensemble, num_reals=None) #3try: import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt import pyproj # except: # return stamen_terrain = cimgt.StamenTerrain() zoom = 10 def fig_ax_gen(): fig = plt.figure(figsize=(20,20)) nrow,ncol = 5,4 axes = [] for i in range(nrow*ncol): #print(i) ax = plt.subplot(nrow,ncol,i+1,projection=stamen_terrain.crs) ax.set_extent([-97.775, -97.625, 30.2, 30.35]) #ax.set_extent([175.2, 176.2, -37, -38.2]) ax.add_image(stamen_terrain,zoom) #plt.show() axes.append(ax) #break return fig, axes #fig,axes = fig_ax_gen() #plt.show() #return pcolormesh_trans = ccrs.UTM(zone=14) pyemu.helpers.plot_flopy_par_ensemble(mc.pst, mc.parensemble, num_reals=None,fig_axes_generator=fig_ax_gen, pcolormesh_transform=pcolormesh_trans,model="freyberg.nam") os.chdir("..")
def plot_map(ds, buffer=None, background='_default', imscale=6, gridlines=True, coastlines=True, scalebar=True, gridlines_kwargs={}): """ Show the boundary of the dataset on a visually appealing map. Parameters ---------- ds : xr.Dataset or xr.DataArray The dataset whose bounds to plot on the map. buffer : float, optional Margin around the bounds polygon to plot, relative to the polygon dimension. By default, add around 20% on each side. background : :class:`cartopy.io.img_tiles` image tiles, optional The basemap to plot in the background (default: Stamen terrain). If None, do not plot a background map. imscale : int, optional The zoom level of the background image (default: 6). gridlines : bool, optional Whether to plot gridlines (default: True). coastlines : bool, optional Whether to plot coastlines (default: True). scalebar : bool, optional Whether to add a scale bar (default: True). gridlines_kwargs : dict, optional Additional keyword arguments for gridlines_with_labels(). Returns ------- :class:`cartopy.mpl.geoaxes.GeoAxes` The corresponding GeoAxes object. """ if background == '_default': try: background = cimgt.Stamen('terrain-background') except AttributeError: # cartopy < 0.17.0 background = cimgt.StamenTerrain() # Get polygon shape # ----------------- geometry_data = shapely.geometry.box(*ds.nd.bounds) if buffer is None: buffer = 1.2 else: buffer += 1.0 buffered = shapely.affinity.scale(geometry_data, xfact=buffer, yfact=buffer) project = pyproj.Transformer.from_crs(ds.nd.crs, 'epsg:4326') b = shapely.ops.transform(project.transform, buffered).bounds extent = [b[0], b[2], b[1], b[3]] bb = Bbox.from_extents(extent) # Define Orthographic map projection # (centered at the polygon) # ---------------------------------- map_crs = _get_orthographic_projection(ds) proj4_params = map_crs.proj4_params if 'a' in proj4_params: # Some version of cartopy add the parameter 'a'. # For some reason, the CRS cannot be parsed by rasterio with # this parameter present. del proj4_params['a'] # Create figure # ------------- ax = plt.axes(xlim=(b[0], b[2]), ylim=(b[1], b[3]), projection=map_crs, aspect='equal', clip_box=bb) ax.set_global() ax.set_extent(extent, crs=ccrs.PlateCarree()) ax.apply_aspect() # Add additional map features # --------------------------- if background is not None: ax.add_image(background, imscale) if coastlines: color = 'black' if background is None else 'white' ax.coastlines(resolution='10m', color=color) if scalebar: # Determine optimal length scale = _get_scalebar_length(ax) scale_bar(ax, (0.05, 0.05), scale, linewidth=5, ha='center') # Add polygon # ----------- geometry_map = warp.get_geometry(ds, crs=proj4_params) ax.add_geometries([geometry_map], crs=map_crs, facecolor=(1, 0, 0, 0.2), edgecolor=(0, 0, 0, 1)) if gridlines: color = '0.5' if background is None else 'white' gridlines_with_labels(ax, color=color, **gridlines_kwargs) return ax
def plot_station_mapping( target_latitude, target_longitude, isd_station, distance_meters, target_label="target", ): # pragma: no cover """ Plots this mapping on a map.""" try: import matplotlib.pyplot as plt except ImportError: raise ImportError("Plotting requires matplotlib.") try: import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.io.img_tiles as cimgt except ImportError: raise ImportError("Plotting requires cartopy.") lat, lng = isd_station.coords t_lat, t_lng = float(target_latitude), float(target_longitude) # fiture fig = plt.figure(figsize=(16, 8)) # axes tiles = cimgt.StamenTerrain() ax = plt.subplot(1, 1, 1, projection=tiles.crs) # offsets for labels x_max = max([lng, t_lng]) x_min = min([lng, t_lng]) x_diff = x_max - x_min y_max = max([lat, t_lat]) y_min = min([lat, t_lat]) y_diff = y_max - y_min xoffset = x_diff * 0.05 yoffset = y_diff * 0.05 # minimum left = x_min - x_diff * 0.5 right = x_max + x_diff * 0.5 bottom = y_min - y_diff * 0.3 top = y_max + y_diff * 0.3 width_ratio = 2. height_ratio = 1. if (right - left) / (top - bottom) > width_ratio / height_ratio: # too short goal = (right - left) * height_ratio / width_ratio diff = goal - (top - bottom) bottom = bottom - diff / 2. top = top + diff / 2. else: # too skinny goal = (top - bottom) * width_ratio / height_ratio diff = goal - (right - left) left = left - diff / 2. right = right + diff / 2. ax.set_extent([left, right, bottom, top]) # determine zoom level # tile size at level 1 = 64 km # level 2 = 32 km, level 3 = 16 km, etc, i.e. 128/(2^n) km N_TILES = 600 # (how many tiles approximately fit in distance) km = distance_meters / 1000.0 zoom_level = int(np.log2(128 * N_TILES / km)) ax.add_image(tiles, zoom_level) # line between plt.plot( [lng, t_lng], [lat, t_lat], linestyle="-", dashes=[2, 2], transform=ccrs.Geodetic(), ) # station ax.plot(lng, lat, "ko", markersize=7, transform=ccrs.Geodetic()) # target ax.plot(t_lng, t_lat, "ro", markersize=7, transform=ccrs.Geodetic()) # station label station_label = "{} ({})".format(isd_station.usaf_id, isd_station.name) ax.text(lng + xoffset, lat + yoffset, station_label, transform=ccrs.Geodetic()) # target label ax.text(t_lng + xoffset, t_lat + yoffset, target_label, transform=ccrs.Geodetic()) # distance labels mid_lng = (lng + t_lng) / 2 mid_lat = (lat + t_lat) / 2 dist_text = "{:.01f} km".format(km) ax.text(mid_lng + xoffset, mid_lat + yoffset, dist_text, transform=ccrs.Geodetic()) plt.show()
def __make_plots__(cube_list, save_filepath, figsize=(16, 9), terrain=cimgt.StamenTerrain(), logscaled=True, vmin=None, vmax=None, colourmap='viridis', colourbarticks=None, colourbarticklabels=None, colourbar_label=None, markerpoint=None, markercolor='#B9DC0C', timestamp=None, time_box_position=None, plottitle=None, box_colour='#FFFFFF', textcolour='#000000', coastlines=False, scheduler_address=None): cubenumber, cube = cube_list if type(figsize) == tuple: fig, ax = plt.subplots(figsize=figsize) Terrain = terrain fig = plt.axes(projection=Terrain.crs) fig.add_image(terrain, 4) if logscaled == True and vmin == None and vmax == None and colourmap == 'viridis': data = iplt.pcolormesh(cube, alpha=1, norm=colors.LogNorm(), cmap='viridis') if logscaled == True and type(vmin) == float and type( vmax) == float and colourmap == 'viridis': data = iplt.pcolormesh(cube, alpha=1, norm=colors.LogNorm(vmin=vmin, vmax=vmax), cmap='viridis') if logscaled == True and vmin == None and vmax == None and type( colourmap) == str: data = iplt.pcolormesh(cube, alpha=1, norm=colors.LogNorm(), cmap=colourmap) if logscaled == True and type(vmin) == float and type( vmax) == float and type(colourmap) == str: data = iplt.pcolormesh(cube, alpha=1, norm=colors.LogNorm(vmin=vmin, vmax=vmax), cmap=colourmap) if logscaled == False and vmin == None and vmax == None and colourmap == 'viridis': data = iplt.pcolormesh(cube, alpha=1, norm=colors.LogNorm(), cmap='viridis') if logscaled == False and type(vmin) == float and type( vmax) == float and colourmap == 'viridis': data = iplt.pcolormesh(cube, alpha=1, vmin=vmin, vmax=vmax, cmap='viridis') if logscaled == False and vmin == None and vmax == None and type( colourmap) == str: data = iplt.pcolormesh(cube, alpha=1, cmap=colourmap) if logscaled == False and type(vmin) == float and type( vmax) == float and type(colourmap) == str: data = iplt.pcolormesh(cube, alpha=1, vmin=vmin, vmax=vmax, cmap=colourmap) if coastlines == True: plt.gca().coastlines('50m') cbaxes = plt.axes([0.2, 0.25, 0.65, 0.03]) colorbar = plt.colorbar(data, cax=cbaxes, orientation='horizontal') colorbar.set_ticks(colourbarticks) colorbar.set_ticklabels(colourbarticklabels) if colourbar_label is not None: colorbar.set_label(colourbar_label, fontproperties='FT2Font', color=box_colour, fontsize=8, bbox=dict(facecolor=box_colour, edgecolor='#2A2A2A', boxstyle='square')) if markerpoint is not None and markercolor is not None: longitude, latitude, name_of_place = markerpoint fig.plot(longitude, latitude, marker='^', color=markercolor, markersize=12, transform=ccrs.Geodetic()) geodetic_transform = ccrs.Geodetic()._as_mpl_transform(fig) text_transform = offset_copy(geodetic_transform, units='dots', y=+75) fig.text(longitude, latitude, u + name_of_place, fontproperties='FT2Font', alpha=1, fontsize=8, verticalalignment='center', horizontalalignment='right', transform=text_transform, bbox=dict(facecolor=markercolor, edgecolor='#2A2A2A', boxstyle='round')) if timestamp is not None: attributedict = subset.attributes datetime = attributedict.get(timestamp) timetransform = offset_copy(geodetic_transform, units='dots', y=0) longitude_of_time_box, latitude_of_time_box = time_box_position fig.text(longitude_of_time_box, latitude_of_time_box, "Time, date: " + datetime, fontproperties='FT2Font', alpha=0.7, fontsize=8, transform=timetransform, bbox=dict(facecolor=markercolor, edgecolor='#2A2A2A', boxstyle='round')) if plottitle is not None: titleaxes = plt.axes([0.2, 0.8, 0.65, 0.04], facecolor=box_colour) titleaxes.text(0.5, 0.25, plottitle, horizontalalignment='center', fontproperties='FT2Font', fontsize=10, weight=600, color=textcolour) titleaxes.set_yticks([]) titleaxes.set_xticks([]) picturename = save_filepath + "%04i.png" % cubenumber plt.savefig(picturename, dpi=200, bbox_inches="tight")
def make_map_images(evid, time, lon, lat, s): time = [] for i in range(len(evid)): x = (evid[i]).split('_') time.append(datetime(int(x[0]), int(x[1]), int(x[2]), int(x[3]), int(x[4]), int(x[5]))) #2010 #data = np.column_stack((time[0:2100], a['lon'][0:2100], a['lat'][0:2100], a['log_stressdrop'][0:2100])) #elmayor, march20 - May20 # data = np.column_stack((time[89:1550], a['lon'][89:1550], a['lat'][89:1550], a['log_stressdrop'][89:1550])) # data = np.column_stack((time[89:1550], lon[89:1550], lat[89:1550], s[89:1550])) data = np.column_stack((time, lon, lat, s)) ## if data in first time bin res = [] # end of first bin: # binstart = datetime(2010, 03, 20, 00, 00, 00) binstart = datetime(2010, 01, 01, 00, 00, 00) res.append([binstart, data[0]]) delta = timedelta(hours = 6) # iterate through the data item for d in data: #print d[0] # if the data item belongs to this bin, append it into the bin if d[0] < binstart + delta: res[-1].append([d[0], d[1], d[2], d[3]]) continue # otherwise, create new empty bins until this data fits into a bin binstart += delta while d[0] > binstart + delta: res.append([binstart, []]) binstart += delta # create a bin with the data res.append([binstart, [d[0], d[1], d[2], d[3]]]) x = [0] y = [0] label = [] sdrop = [-1] cmap = mpl.cm.get_cmap('gist_rainbow') normalize = mpl.colors.Normalize(vmin=min(s), vmax= max(s)) colors = [cmap(normalize(value)) for value in s] s_m = mpl.cm.ScalarMappable(cmap = cmap, norm=normalize) s_m.set_array([]) stamen_terrain = cimgt.StamenTerrain(desired_tile_form="L") fig = plt.figure(figsize = (18,16.2)) plt.tight_layout() ax = plt.axes(projection=stamen_terrain.crs) #entire region #ax.set_extent([-118.01, -114.99, 32.29, 34.41]) #2010 region #ax.set_extent([-116.51, -114.99, 32.29, 33.21]) #elMayor region ax.set_extent([-116.2, -115.1, 32.29, 33.0]) c = [cmap(normalize(value)) for value in sdrop] ax.add_image(stamen_terrain, 10, alpha = 0.5, cmap = 'gray', zorder = 3) plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='both', length = 5, width = 1) plt.title(label, fontsize = 26) #entire region # xticks = [-118, -117, -116, -115] # yticks = [32.3, 33, 33.5, 34, 34.4] #2010 xticks = [-117,-116.5, -116, -115.5, -115, -114] yticks = [32, 32.3, 32.5, 32.7, 32.9, 33.1, 33.3] ax.gridlines(xlocs=xticks, ylocs=yticks, draw_labels = True) for segment_i in range(len(fault_segments)): fault=fault_segments[segment_i] fault_z=np.zeros(len(fault)) ax.plot(fault[:,0],fault[:,1],fault_z,color='k', transform=ccrs.Geodetic()) ax.scatter(x, y, marker='o', color= c, s=50, alpha=1.0, transform=ccrs.Geodetic()) # geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) fig.subplots_adjust(right=0.88) cbar_ax = fig.add_axes([0.92, 0.1, 0.02, 0.8]) cbar = plt.colorbar(s_m, cax=cbar_ax) cbar.set_label(ur"stressdrop", fontsize = 22)#"$azimuth$ (\u00b0)" cbar.ax.tick_params(labelsize = 18) #for each bin for i in range(len(res)): x = [0] y = [0] #label = [] sdrop = [] #print i binned_data = res[i][1:] label = res[i][0] if binned_data != [[]]: for j in range(len(binned_data)): x.append(binned_data[j][1]) y.append(binned_data[j][2]) #label.append(binned_data[i][0]) sdrop.append(binned_data[j][3]) c = [cmap(normalize(value)) for value in sdrop] ax.set_title(label, fontsize = 26, y = 1.05) ax.scatter(x, y, marker='o', color= c, s=60, alpha=1.0, transform=ccrs.Geodetic()) #plt.show() plt.savefig(top_dir + '/source_params/map_images_delta6hr/img' + str(i).zfill(5) + '.png')
def points_in_poly(vertices, s, sig, name, lat, lon, m, d, x0, x1, save, days): ''' finds points in a polygon from vertices plots polygon on stressdrop map plots stressdrop versus time and stressdrop vs mag/depth Input: vertices: array of vertex points of polygon s: list/array of event log stress drops sig: list/array of event log stress drops sigma name: string name of polygon lat: list/array of event latitudes lon: list/array of event longitudes m: list/array of event magnitudes d: list/array of event depths (km) x0: utc datetime, first in range for plotting x1: utc datetime, first in range for plotting save: True or False to save Output: plots 2 scatter plots of stress drop vs mag and stress drop versus depth ''' import matplotlib.pyplot as plt import matplotlib as mpl from shapely.geometry.polygon import Polygon import matplotlib.path as mpltPath import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt poly = Polygon(vertices) x,y = poly.exterior.xy cmap = mpl.cm.get_cmap('gist_rainbow') normalize = mpl.colors.Normalize(vmin=min(s), vmax=max(s)) colors = [cmap(normalize(value)) for value in s] s_m = mpl.cm.ScalarMappable(cmap = cmap, norm=normalize) s_m.set_array([]) stamen_terrain = cimgt.StamenTerrain(desired_tile_form="L") fig = plt.figure(figsize = (18,16)) ax = plt.axes(projection=stamen_terrain.crs) ax.set_extent([-118.01, -114.99, 32.29, 34.41]) ax.add_image(stamen_terrain, 10, alpha = 0.5, cmap = 'gray') plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='both', length = 5, width = 1) xticks = [-118, -117, -116, -115] yticks = [32.3, 33, 33.5, 34, 34.4] ax.gridlines(xlocs=xticks, ylocs=yticks, draw_labels = True) for segment_i in range(len(fault_segments)): fault=fault_segments[segment_i] fault_z=np.zeros(len(fault)) ax.plot(fault[:,0],fault[:,1],fault_z,color='k', transform=ccrs.Geodetic()) plt.scatter(lon, lat, marker='o', color= colors, s=25, alpha=1.0, transform=ccrs.Geodetic()) plt.plot(x, y, color = 'blue', transform=ccrs.Geodetic()) # geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) fig.subplots_adjust(right=0.88) cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.75]) cbar = plt.colorbar(s_m, cax=cbar_ax) cbar.set_label(ur"stressdrop", fontsize = 22)#"$azimuth$ (\u00b0)" cbar.ax.tick_params(labelsize = 18) plt.savefig(top_dir + '/source_params/polygon/polygon_' + name + '.png') plt.show() points = zip(lon,lat) path = mpltPath.Path(vertices) inside = path.contains_points(points) ev = [] t = [] s = [] m = [] sig = [] d = [] for i in range(len(inside)): if inside[i] == True: x = (sobj.evid[i]).split('_') x = (datetime(int(x[0]), int(x[1]), int(x[2]), int(x[3]), int(x[4]), int(x[5]))) #if in time range if (x >= x0) and (x <= x1): x = (sobj.evid[i]).split('_') ev.append(sobj.evid[i]) t.append(datetime(int(x[0]), int(x[1]), int(x[2]), int(x[3]), int(x[4]), int(x[5]))) s.append(sobj.log_stressdrop[i]) m.append(sobj.m_cat[i]) sig.append(sobj.log_stressdrop_sig[i]) d.append(sobj.depth[i]) stressdrop_vs_time(ev = ev, lat = lat, lon = lon, s = s, sig = sig, m = m, name = name, x0 = x0, x1 = x1, save = save, days = days, regions = False) stressdrop_vs_time(ev = ev, lat = lat, lon = lon, s = s, sig = sig, m = m, name = name + '_entire_window', x0 = datetime(2010, 01, 01, 0, 0, 0), x1 = datetime(2017, 01, 01, 0, 0, 0), save = save, days = 90, regions = False) stressdrop_vs_depth_mag(s = s, d = d, mag = m, sig = sig, name = name, save = save)
def stressdrop_map(s, lat, lon, save, regions): ''' Maps stress drops for all event on map Input: s: list/array of log stressdrops lat: list/array of event latitudes lon: list/array of event longitudes save: yes or no to save figure Output: plots a map ''' import matplotlib.pyplot as plt import matplotlib as mpl import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt cmap = mpl.cm.get_cmap('gist_rainbow') normalize = mpl.colors.Normalize(vmin=min(s), vmax=max(s)) colors = [cmap(normalize(value)) for value in s] s_m = mpl.cm.ScalarMappable(cmap = cmap, norm=normalize) s_m.set_array([]) stamen_terrain = cimgt.StamenTerrain(desired_tile_form="L") fig = plt.figure(figsize = (18,16)) ax = plt.axes(projection=stamen_terrain.crs) ax.set_extent([-118.01, -114.99, 32.29, 34.41]) ax.add_image(stamen_terrain, 10, alpha = 0.5, cmap = 'gray') plt.tick_params(axis='both', which='major', labelsize=18) plt.tick_params(axis='both', which='both', length = 5, width = 1) xticks = [-118, -117, -116, -115] yticks = [32.3, 33, 33.5, 34, 34.4] ax.gridlines(xlocs=xticks, ylocs=yticks, draw_labels = True) for segment_i in range(len(fault_segments)): fault=fault_segments[segment_i] fault_z=np.zeros(len(fault)) ax.plot(fault[:,0],fault[:,1],fault_z,color='k', transform=ccrs.Geodetic()) plt.scatter(lon, lat, marker='o', color= colors, s=30, alpha=1.0, transform=ccrs.Geodetic()) # geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) #if regions is True, add polygons if regions == True: for i in range(len(vertex_list)): poly = Polygon(vertex_list[i]) x,y = poly.exterior.xy plt.plot(x,y, color = color[i], transform=ccrs.Geodetic(), label = labels[i], lw = 2) plt.legend(loc=(0.1,-0.15),ncol=4) fig.subplots_adjust(right=0.88) cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.75]) cbar = plt.colorbar(s_m, cax=cbar_ax) cbar.set_label(ur"stressdrop", fontsize = 22)#"$azimuth$ (\u00b0)" cbar.ax.tick_params(labelsize = 18) plt.show() if save == True: plt.savefig(top_dir + '/source_params/stressdrop_map_regions.png')
def makeFigure2_BasinMap(): demands = pd.read_csv('../Structures_files/demands.csv', index_col=0) structures = pd.read_csv('../Structures_files/modeled_diversions.csv', index_col=0) for index, row in structures.iterrows(): structures.at[str(index), 'Mean demand'] = np.mean(demands.loc[str(index)].values) extent = [-109.069, -105.6, 38.85, 40.50] extent_large = [-111.0, -101.0, 36.5, 41.5] rivers_10m = cpf.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '10m') tiles = cimgt.StamenTerrain() shape_feature = ShapelyFeature(Reader( '../Structures_files/Shapefiles/Water_Districts.shp').geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='None') flow_feature = ShapelyFeature( Reader('../Structures_files/Shapefiles/UCRBstreams.shp').geometries(), ccrs.PlateCarree(), edgecolor='royalblue', facecolor='None') fig = plt.figure(figsize=(18, 9)) ax = plt.axes(projection=tiles.crs) ax.add_image(tiles, 9, interpolation='none', alpha=0.8) ax.set_extent(extent) ax.add_feature(shape_feature, facecolor='#a1a384', alpha=0.6) ax.add_feature(flow_feature, alpha=0.6, linewidth=1.5, zorder=4) ax.scatter(structures['X'], structures['Y'], marker='.', s=50, c='black', transform=ccrs.Geodetic(), zorder=5) fig.savefig('Figure2_Basin.pdf') fig.clf() geom = geometry.box(extent[0], extent[2], extent[1], extent[3]) fig = plt.figure(figsize=(18, 9)) ax = plt.axes(projection=tiles.crs) ax.add_feature(rivers_10m, facecolor='None', edgecolor='royalblue', linewidth=2, zorder=4) ax.add_image(tiles, 7, interpolation='none', alpha=0.8) ax.set_extent(extent_large) ax.add_feature(cpf.STATES) ax.add_geometries( [geom], crs=ccrs.PlateCarree(), facecolor='None', edgecolor='black', linewidth=2, ) ax.add_feature(shape_feature, facecolor='#a1a384', alpha=0.6) fig.savefig('Figure2_Inset.pdf') fig.clf() return None
def render_map(time_current, ships, margin, plot=False): # Get base map # cimgt.StamenTerrain() zoom-level 12 or 13 # cimgt.GoogleTiles(style="satellite") # cimgt.GoogleTiles(style="terrain") # cimgt.MapboxTiles ! (More args required) # cimgt.MapQuestOpenAerial (Error downloading tiles) # cimgt.MapQuestOSM # cimgt.QuadtreeTiles # cimgt.OSM basemap_tiles = CachedTiler(cimgt.StamenTerrain()) zoom_level = 12 min_lon = min([s[0].min_lon for s in ships]) max_lon = max([s[0].max_lon for s in ships]) min_lat = min([s[0].min_lat for s in ships]) max_lat = max([s[0].max_lat for s in ships]) d_lon = max_lon - min_lon d_lat = max_lat - min_lat # set up axes fig = plt.figure() fig.set_size_inches(20, 10) ax = plt.axes(projection=basemap_tiles.crs) # Create a GeoAxes in the tile's projection. ax.set_extent([min_lon - margin * d_lon, max_lon + margin * d_lon, min_lat - margin * d_lat, max_lat + margin * d_lat]) # Limit extent to track bounding box. ax.add_image(basemap_tiles, zoom_level) # Add the basemap data at zoom level 8. # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. # geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) # text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add Title, Legend, Time indicator plt.title(time_current.strftime("%Y-%m-%d")) ship_names = [s[0].meta["name"] for s in ships] ship_colors = [s[0].meta["color"] for s in ships] legend_artists = [Line([0], [0], color=color, linewidth=1) for color in ship_colors] legend = plt.legend(legend_artists, ship_names, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('none') plt.annotate(str(time_current.strftime("%H:%M UTM")), xy=(0.5, 0.05), xycoords='axes fraction') # Add ship tracks for ship in ships: vertices = sgeom.LineString(zip(ship[0].lons(max_time=time_current), ship[0].lats(max_time=time_current))) ax.add_geometries([vertices], ccrs.PlateCarree(), facecolor='none', edgecolor=ship[0].meta["color"]) # Add a marker for the ships last location last_pos = ship[0].last_position_at_time(time_current) last_info = ship[0].last_info_at_time(time_current) plt.plot(last_pos[0], last_pos[1], marker=(3, 0, last_info[0]), color=ship[0].meta["color"], markersize=5, alpha=1, transform=ccrs.PlateCarree()) # plt.annotate("Shelby: {:.1f} kts".format(last_info[1] * 1.94384), xy=(0.9, 0.05), xycoords='axes fraction') # plt.annotate("Elixir: {:.1f} kts".format(last_info[1] * 1.94384), xy=(0.9, 0.05), xycoords='axes fraction') # finalize if plot: plt.show() return fig
def make_plots(cube_list, save_filepath, figsize=(16, 9), terrain=cimgt.StamenTerrain(), logscaled=True, vmin=None, vmax=None, colourmap='viridis', colourbarticks=None, colourbarticklabels=None, colourbar_label=None, markerpoint=None, markercolor='#B9DC0C', timestamp=None, time_box_position=None, plottitle=None, box_colour='#FFFFFF', textcolour=None, coastlines=False, scheduler_address=None): """ Makes plots from list of iris cubes. Args: cube_list: Takes list of cubes. save_filepath: Filepath where the plots will be saved. Ensure filepath is empty of any other files before creating video. Kwargs: figsize: Sets size of figure. Default is 16 in x 9 in. Takes a tuple of integers or floats (e.g. (16, 9)). terrain: Sets background map image on plot. Default is Stamen Terrain. See further options here: https://scitools.org.uk/cartopy/docs/latest/cartopy/io/img_tiles.html logscaled: Plots data on a logarithmic (to the base-10) scale. Takes True or False. Makes more appealing visualisations of skewed data. Default is True. vmin: set lowest value to be displayed. Takes a float. vmax: set highest value to be displayed. Takes a float. colourmap: Sets colour map for the plot. Default is 'viridis'. Other colourmaps: 'magma', 'plasma', 'inferno', 'cividis'. See https://matplotlib.org/tutorials/colors/colormaps.html for more colourmap options. colourbarticks: Sets position within data of ticks on colourbar. Takes a list of floats or integers, e.g. [10, 100, 1000]. colourbarticklabels: Sets labels for colourbar ticks. Takes a list, eg. [10, 100, 1000]. colourbar_label: Sets colourbar legend. Takes a string. markerpoint: Plots a marker on the map based on global coordinates. Takes a tuple in this format - (longitude, latitude, 'name_of_place'), longitude and latitude must be a float, name_of_place must be a string. markercolor: Color of the location marker. Must be given as a string. Default is '#B9DC0C'. timestamp: Places a timestamp box on each plot. Takes a string referring to name of timestep metadata within the cube. It must contain timesteps in original metadata to use this, as this takes the name of the timestep attribute. plottitle: Displays the title of your video horizontally across the top of the plots. Takes a string. time_box_position: Position of timestamp box on the plot. Takes a tuple of integers eg. (60, 0) box_colour: Sets colour of title box and colourbar label box. Takes a string. textcolor: Sets colour of text within boxes. Takes a string. coastlines: Draw coastlines around land on the map. Takes True or False. For optimal runtime, specify own dask client. If dask errors are raised, ensure that lenny has been installed on the workers. """ from dask import delayed import dask.bag as db from distributed import Client from dask_kubernetes import KubeCluster if scheduler_address is not None: client = scheduler_address client.run(lambda: sys.path.append(save_filepath)) makingplots = db.from_sequence(cube_list).map( __make_plots__, save_filepath, figsize, terrain, logscaled, vmin, vmax, colourmap, colourbarticks, colourbarticklabels, colourbar_label, markerpoint, markercolor, timestamp, time_box_position, plottitle, box_colour, textcolour, coastlines) plots = makingplots.compute() if scheduler_address == None: client = Client() client.run(lambda: sys.path.append(save_filepath)) makingplots = db.from_sequence(cube_list).map( __make_plots__, save_filepath, figsize, terrain, logscaled, vmin, vmax, colourmap, colourbarticks, colourbarticklabels, colourbar_label, markerpoint, markercolor, timestamp, time_box_position, plottitle, box_colour, textcolour, coastlines) plots = makingplots.compute()
def main(forest): # dem = pcr.readmap('../Data/DEM.map') # DEM = pcr.pcr2numpy(dem, 9999) # DEM[DEM==9999]=np.nan stamen_terrain = cimgt.StamenTerrain() proj = ccrs.AlbersEqualArea(central_longitude=-110, central_latitude=45.5,standard_parallels=(29.5,45.5)) ax = plt.axes(projection=proj) #ax.outline_patch.set_visible(False) # minx = -1446763 # maxy = 2732249 # maxx = -1340013 # miny = 2615749 # # x = np.linspace(minx,maxx,DEM.shape[1]) # y = np.linspace(miny,maxy,DEM.shape[0]) # xx, yy = np.meshgrid(x,y) # data = np.flipud(DEM) # colormesh = ax.pcolor(xx, yy, data, # transform=proj, # cmap='spring_r',linewidth=0,alpha = .3,vmin=10000,vmax=32000) ax.add_image(stamen_terrain,4) datapath = '../Data/Processed/' df23June = pd.read_csv(datapath + 'df23June.csv') print list(df23June) #df23June = df23June[df23June.Stock_Type == '1-0'] #df23June = df23June[df23June.Stakes >= 30] #df23June = df23June[df23June.Species != 'ES'] #df23June = df23June[df23June.Stock_Type != 'LP'] pcount = 0 for index,column in df23June.iterrows(): plt.plot(column['Longitude'],column['Latitude'],'d',markersize=4,color = 'red',label='Wheat') pcount +=1 #plt.plot(-583100,3062000,'.',color='white',label='Correct') #plt.plot(-583100,3062000,'.',color='black',label='Incorrect') #x = np.linspace(-1550000,-1550001,2) #y = np.linspace(29000000,29000001,2) #xx, yy = np.meshgrid(x,y) #data = xx/xx*.5 #colormesh = ax.pcolor(xx, yy,data , # transform=proj, # cmap='spectral',linewidth=0,vmin=0,vmax=20) #plt.plot(-583100,3262000,'.',color='white',label='_nolegend_') #plt.plot(-2500000,1062000,'.',color='white',label='_nolegend_') #ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') ax.add_feature(cfeature.BORDERS) ax.add_feature(states_provinces, edgecolor='black') plt.legend(loc=3) scale_bar(ax,50) #plt.savefig('../Figures/Seedling_defense.png') plt.show()
# Combine and subset time and fire radiative power times = [ datetime.datetime(1900, 1, 1) + datetime.timedelta(hours=hours) for hours in np.concatenate([ds['time'][:] for ds in datasets]) ] frp = np.vstack([ds['frpfire'][:, use_lat][:, :, use_lon] for ds in datasets]) # Use plateCarree projection for lat/lon data cproj = ccrs.PlateCarree() # Create matplotlib figure and axes fig = plt.gcf() fig.set_size_inches(18.5, 10.5) fig.subplots_adjust(left=0, right=1, bottom=0.02, top=0.95) stamen_terrain = cimgt.StamenTerrain() ax_1 = plt.subplot(1, 2, 1, projection=stamen_terrain.crs) ax_2 = plt.subplot(1, 2, 2, projection=stamen_terrain.crs) ax_1.add_image(stamen_terrain, 6) ax_2.add_image(stamen_terrain, 6) map_extent = [ country_bbox[1] - 2, country_bbox[3] + 2, country_bbox[0] - 2, country_bbox[2] + 2 ] ax_1.set_extent(map_extent, cproj) ax_2.set_extent(map_extent, cproj)