def map_stress_plot(params, inputs, out_object, stress_component): """ Using PyGMT Filling in fault patches with colors corresponding to their stress changes """ if stress_component == 'shear': plotting_stress = out_object.receiver_shear label = 'Shear' elif stress_component == 'normal': plotting_stress = out_object.receiver_normal label = 'Normal' else: plotting_stress = out_object.receiver_coulomb # The default option label = 'Coulomb' if not out_object.receiver_object: return # Make stress bounds for color map. vmin, vmax = -1, 1 [cmap_opts, cbar_opts] = utilities.define_colorbar_series(plotting_stress, vmin=vmin, vmax=vmax) # Make cpt pygmt.makecpt(cmap="jet", series=str(cmap_opts[0]) + "/" + str(cmap_opts[1]) + "/" + str(cmap_opts[2]), output="mycpt.cpt", background=True) # Make Map region = [inputs.minlon, inputs.maxlon, inputs.minlat, inputs.maxlat] proj = "M7i" fig = pygmt.Figure() title = "+t\"" + stress_component + " stress\"" # must put escaped quotations around the title. fig.basemap(region=region, projection=proj, frame=title) fig.coast(shorelines="1.0p,black", region=region, borders="1", projection=proj, frame="1.0") # the boundary. fig.coast(region=region, projection=proj, borders='2', shorelines='0.5p,black', water='white', map_scale="g-125.5/39.6+c1.5+w50") fig = annotate_figure_with_sources(fig, inputs, params) # Draw each receiver, with associated data for i in range(len(out_object.receiver_object)): rec = out_object.receiver_object[i] [x_total, y_total, _, _] = conversion_math.get_fault_four_corners(rec) lons, lats = fault_vector_functions.xy2lonlat(x_total, y_total, inputs.zerolon, inputs.zerolat) fig.plot(x=lons, y=lats, zvalue=str(plotting_stress[i]), pen="thick,black", color="+z", cmap="mycpt.cpt") # color = stress # Colorbar annotation fig.coast(shorelines="1.0p,black", region=region, projection=proj) # the boundary. fig.colorbar(position="jBr+w3.5i/0.2i+o2.5c/1.5c+h", cmap="mycpt.cpt", shading="0.8", truncate=str(cbar_opts[0]) + "/" + str(cbar_opts[1]), frame=["x" + str(0.2), "y+L\"KPa\""]) # Annotate with aftershock locations fig = annotate_figure_with_aftershocks(fig, aftershocks_file=params.aftershocks, style='c0.02c') fig.savefig(params.outdir + label + '_map.png') return
name the new column of values sampled from the grid. Alternatively, a NetCDF file path can be passed to ``grid``. An ASCII file path can also be accepted for ``points``. To save an output ASCII file, a file name argument needs to be passed to the ``outfile`` parameter. """ import pygmt # Load sample grid and point datasets grid = pygmt.datasets.load_earth_relief() points = pygmt.datasets.load_ocean_ridge_points() # Sample the bathymetry along the world's ocean ridges at specified track points track = pygmt.grdtrack(points=points, grid=grid, newcolname="bathymetry") fig = pygmt.Figure() # Plot the earth relief grid on Cylindrical Stereographic projection, masking land areas fig.basemap(region="g", projection="Cyl_stere/150/-20/15c", frame=True) fig.grdimage(grid=grid, cmap="gray") fig.coast(land="#666666") # Plot the sampled bathymetry points using circles (c) of 0.15 cm # Points are colored using elevation values (normalized for visual purposes) fig.plot( x=track.longitude, y=track.latitude, style="c0.15c", cmap="terra", color=(track.bathymetry - track.bathymetry.mean()) / track.bathymetry.std(), ) fig.show()
import numpy as np np.random.seed(42) region = [150, 240, -10, 60] x = np.random.uniform(region[0], region[1], 20) y = np.random.uniform(region[2], region[3], 20) z = np.random.uniform(1,5,20) print("x:\n", x) print("y:\n", y) print("z:\n", z) #%% # 通过 :meth:`pygmt.Figure.plot` 绘制符号时需要用 ``style`` 选项控制符号类型和大小: import pygmt fig = pygmt.Figure() fig.basemap(region=region, projection="X8c", frame=True) # 绘制三角符号(i),大小为 0.5 厘米(0.5c) fig.plot(x, y, style="i0.5c", color="black") fig.show() #%% # 大小变化的符号 # ----------------- # # 绘制大小变化的符号时在选项 ``style`` 中说明 # 符号类型和单位,由 ``sizes`` 控制符号大小: fig = pygmt.Figure() fig.basemap(region=region, projection="X8c", frame=["nSWe","af"]) # 绘制五角星符号(a),单位为厘米(c),大小由 sizes 控制
def map_displacement_vectors(params, inputs, obs_disp_points, out_object, outfile, vmin=None, vmax=None): """ Make a plot of modeled vector displacement from model_disp_points obs_disp_points is an object that can be used to also plot observations at the same points. """ if len(out_object.model_disp_points) == 0: return proj = 'M4i' region = [inputs.minlon, inputs.maxlon, inputs.minlat, inputs.maxlat] # Unpack model_dE = np.array([x.dE_obs for x in out_object.model_disp_points]) model_dN = np.array([x.dN_obs for x in out_object.model_disp_points]) model_dU = np.array([x.dU_obs for x in out_object.model_disp_points]) model_lon = np.array([x.lon for x in out_object.model_disp_points]) model_lat = np.array([x.lat for x in out_object.model_disp_points]) # Make modeled vertical displacement color map [cmap_opts, cbar_opts] = utilities.define_colorbar_series(model_dU, vmin, vmax) pygmt.makecpt(cmap="roma", series=str(cmap_opts[0]) + "/" + str(cmap_opts[1]) + "/" + str(cmap_opts[2]), background="o", output="mycpt.cpt") # Build a PyGMT plot fig = pygmt.Figure() fig.basemap(region=region, projection=proj, frame="+t\"Coseismic Displacements\"") fig.coast(region=region, projection=proj, borders='1', shorelines='1.0p,black', water='lightblue', map_scale="n0.4/0.06+c" + str(region[2]) + "+w20", frame="1.0") fig.plot(model_lon, model_lat, style='c0.3c', color=model_dU, cmap='mycpt.cpt', pen="thin,black") # Draw vectors and vector scale bar # scale_factor = 1; scale_arrow = 0.100; vectext = "10 cm"; # 10 cm, large vectors scale_factor = 100 scale_arrow = 0.010 vectext = "10 mm" # 10 mm, small vectors # scale_factor = 1000; scale_arrow = 0.002; vectext = "2 mm"; # 1 mm, extra small vectors max_disp = np.max(np.sqrt(np.square(model_dN) + np.square(model_dE))) scale = (max_disp * scale_factor / 0.003) # empirical scaling, convenient display fig.plot(x=model_lon, y=model_lat, style='v0.2c+e+gblack+h0+p1p,black+z' + str(scale), direction=[model_dE, model_dN], pen="thin,black") fig.plot(x=[region[0] + 0.30], y=[region[2] + 0.05], style='v0.2c+e+gblack+h0+p1p,black+z' + str(scale), direction=[[scale_arrow], [0]], pen="thin,black") # scale vector fig.text(x=[region[0] + 0.45], y=[region[2] + 0.15], text=vectext + " model") # scale label # Plot the observations if they exist obs_dE = np.array([x.dE_obs for x in obs_disp_points]) obs_dN = np.array([x.dN_obs for x in obs_disp_points]) if sum(~np.isnan(obs_dE)) > 0: fig.plot(x=model_lon, y=model_lat, style='v0.2c+e+gred+h0+p1p,red+z' + str(scale), direction=[obs_dE, obs_dN], pen="thin,red") fig.plot(x=[region[0] + 0.30], y=[region[2] + 0.35], style='v0.2c+e+gred+h0+p1p,red+z' + str(scale), direction=[[scale_arrow], [0]], pen="thin,red") # scale vector fig.text(x=[region[0] + 0.50], y=[region[2] + 0.45], text=vectext + ' obs') # scale label fig = annotate_figure_with_sources(fig, inputs, params) fig = annotate_figure_with_aftershocks(fig, aftershocks_file=params.aftershocks) fig.colorbar(position="JCR+w4.0i+v+o0.7i/0i", cmap="mycpt.cpt", truncate=str(cbar_opts[0]) + "/" + str(cbar_opts[1]), frame=["x" + str(cbar_opts[2]), "y+L\"Vert Disp(m)\""]) fig.savefig(outfile) return
def pygmt_vertical_map(myparams, ts_objects, vert_slopes): offset = 0.2 geothermals_x = [-115.528300, -115.250000, -115.515300, -115.600000] geothermals_y = [32.716700, 32.783300, 33.015300, 33.200000] lons = [] lats = [] names = [] for i in range(len(ts_objects)): lons.append(ts_objects[i].coords[0]) lats.append(ts_objects[i].coords[1]) names.append(ts_objects[i].name) region = [ min(lons) - offset, max(lons) + offset, min(lats) - offset, max(lats) + offset ] # Make a new color bar min_vert = np.min(vert_slopes) if min_vert < -8: min_vert = -8 max_vert = np.max(vert_slopes) if max_vert - min_vert < 5.0: label_interval = 0.5 else: label_interval = 2.0 pygmt.makecpt(C="jet", T=str(min_vert - 0.1) + "/" + str(max_vert + 0.1) + "/0.1", H="mycpt.cpt") fig = pygmt.Figure() fig.basemap(region=region, projection="M8i", B="0.25") fig.coast(shorelines="0.5p,black", G='peachpuff2', S='skyblue', D="h") fig.coast(N='1', W='1.0p,black') fig.coast(N='2', W='0.5p,black') fig.text(x=[i + 0.035 for i in lons], y=lats, text=names, font='15p,Helvetica-Bold,black') fig.plot(x=geothermals_x, y=geothermals_y, S='i0.2i', G="purple", W='0.5p,black') fig.plot(x=lons, y=lats, S='c0.2i', C="mycpt.cpt", G=vert_slopes, W='0.5p,black') fig.plot(x=myparams.center[0], y=myparams.center[1], S='a0.1i', G='red', W='0.5p,red') fig.colorbar(D="JBC+w4.0i+h", C="mycpt.cpt", G=str(min_vert) + "/" + str(max_vert), B=["x" + str(label_interval), "y+LVelocity(mm/yr)"]) fig.savefig(myparams.outdir + "/" + myparams.outname + '_map.png') return
# %% fig, axarr = plt.subplots(nrows=1, ncols=4, squeeze=False, figsize=(22, 12)) axarr[0, 0].imshow(X_tile[0, 0, :, :], cmap="BrBG") axarr[0, 0].set_title("BEDMAP2") axarr[0, 1].imshow(Y_hat[0, 0, :, :], cmap="BrBG") axarr[0, 1].set_title( "Super Resolution Generative Adversarial Network prediction") axarr[0, 2].imshow(S_tile[0, 0, :, :], cmap="BrBG") axarr[0, 2].set_title("Synthetic High Resolution Grid") groundtruth.plot(ax=axarr[0, 3], cmap="BrBG") axarr[0, 3].set_title("Groundtruth grids") plt.show() # %% fig = gmt.Figure() subplot(directive="begin", row=2, col=2, A="+jCT+o-4c/-5c", Fs="9c/9c", M="2c/3c") plot_3d_view( img="model/deepbedmap3.nc", # DeepBedMap ax=(0, 0), zmin=-1400, title="DeepBedMap", # ours zlabel="Bed elevation (metres)", ) plot_3d_view( img="model/cubicbedmap.nc", # BEDMAP2
def gen_map_image(): # has to be imported at time of use to work with uwsgi try: import pygmt except Exception: os.environ['GMT_LIBRARY_PATH'] = '/usr/local/lib' import pygmt vector_args = {} for arg in [ 'baseline', 'date_from', 'date_to', 'scale', 'station', 'zoom', 'quakes' ]: vector_args[arg] = flask.request.form[arg] map_bounds = json.loads(flask.request.form['map_bounds']) bounds = [ map_bounds['west'], map_bounds['east'], map_bounds['south'], map_bounds['north'] ] date_from = parse(vector_args['date_from']).date() date_to = parse(vector_args['date_to']).date() fig = pygmt.Figure() fig.basemap(projection="M16i", region=bounds, frame=('WeSn', 'afg')) parent_dir = os.path.dirname(__file__) grid = os.path.join(parent_dir, "alaska_2s.grd") fig.grdimage(grid, C='geo', E=300, I=True, M=True) fig.coast(I='r/2p,#FFFFFF', water="#FFFFFF", resolution="f") # Plot the earthquakes (if any) quake_data = json.loads(vector_args['quakes']) quake_df = pd.DataFrame.from_dict(quake_data) if quake_df.size > 0: quake_df['x'] = quake_df.apply(lambda x: x.location['lng'], axis=1) quake_df['y'] = quake_df.apply(lambda x: x.location['lat'], axis=1) quake_df['sizes'] = quake_df.apply( lambda x: .25 * math.exp(0.5 * x.magnitude), axis=1) fig.plot(x=quake_df.x, y=quake_df.y, sizes=quake_df.sizes, style="cc", color="white", pen="black") # Plot the vectors vector_data = _get_vector_data(vector_args['station'], vector_args['baseline'], date_from, date_to, int(vector_args['zoom']), int(vector_args['scale'])) xy_vectors = pd.DataFrame.from_dict([{ 'x': numpy.array((x[0]['lng'], x[1]['lng']), dtype=numpy.float32), 'y': numpy.array((x[0]['lat'], x[1]['lat']), dtype=numpy.float32), } for x in vector_data['xy']]) z_vectors = pd.DataFrame.from_dict([{ 'x': numpy.array((x[0]['lng'], x[1]['lng']), dtype=numpy.float32), 'y': numpy.array((x[0]['lat'], x[1]['lat']), dtype=numpy.float32), } for x in vector_data['z']]) for idx, row in xy_vectors.iterrows(): fig.plot(x=row.x, y=row.y, pen='2.5p,51/0/255+ve0.12i+g51/0/255+a50') for idx, row in z_vectors.iterrows(): fig.plot(x=row.x, y=row.y, pen='2.5p,"#0CDA3B') station_data = pd.DataFrame.from_dict(stations, orient="index") # Figure out circle color and pen color station_data['color'] = station_data.apply( lambda row: 0 if row.type == "continuous" else 1, axis=1) # Split the data frame into two so we can vary the pen color # seperately from the fill color sdata_red = station_data[station_data.has_tilt] sdata_white = station_data[~station_data.has_tilt] fig.plot(x=sdata_red.lng, y=sdata_red.lat, style="c0.5i", color=sdata_red.color, cmap="73/0/244,12/218/59", pen='2p,red') fig.plot(x=sdata_white.lng, y=sdata_white.lat, style="c0.5i", color=sdata_white.color, cmap="73/0/244,12/218/59", pen='2p,white') fig.text(x=station_data.lng, y=station_data.lat, text=station_data.index.tolist(), font="12p,Helvetica-Bold,white") scale_params = _get_scale_parameters(vector_data['scale'], bounds) # Plot the scale bar background fig.plot(data=numpy.array([scale_params['background']]), style='r+s', G="white@75") # And the scale bar itself fig.plot(x=scale_params['x'], y=scale_params['y'], pen='2.5p,51/0/255+ve0.12i+g51/0/255+a50') # some labels date_range = f"{date_from.strftime('%m/%d/%y')}-{date_to.strftime('%m/%d/%y')}" fig.text(x=scale_params['x'][0], y=scale_params['dt'], text=date_range, font="14p,Helvetica", justify="TL") fig.text(x=scale_params['x'][0], y=scale_params['text'], text='1cm/year', font="14p,Helvetica", justify="TL") # fig.show(method = "external") save_file = f'{uuid.uuid4().hex}.pdf' file_path = os.path.join('/tmp', save_file) fig.savefig(file_path) file = open(file_path, 'rb') file_data = file.read() file.close() os.remove(file_path) response = flask.make_response(file_data) response.headers.set('Content-Type', 'application/pdf') response.headers.set('Content-Disposition', 'attachment', filename="MapImage.pdf") return response
def plot_vc(startlon, startlat, endlon, endlat, models, parameter, x_axis_label, depth, colorbar_range, threshold, filename): # fix the problem of possible -R failure if ((x_axis_label == "lon" and startlon > endlon) or (x_axis_label == "lat" and startlat > endlat)): startlon, endlon = endlon, startlon startlat, endlat = endlat, startlat fig = pygmt.Figure() pygmt.config(FONT_LABEL="15p", MAP_LABEL_OFFSET="12p", FONT_ANNOT_PRIMARY="12p", MAP_FRAME_TYPE="plain") pygmt.makecpt( cmap=gmt_get_data_vc("dvs_6p.cpt"), series=f"{colorbar_range[0]/100:.3f}/{colorbar_range[1]/100:.3f}/0.01", continuous=True, D="o") # load izu = xr.open_dataset(get_data_vc("izu_slab2_depth.grd")) kur = xr.open_dataset(get_data_vc("kur_slab2_depth.grd")) phi = xr.open_dataset(get_data_vc("phi_slab2_depth.grd")) ryu = xr.open_dataset(get_data_vc("ryu_slab2_depth.grd")) man = xr.open_dataset(get_data_vc("man_slab2_depth.grd")) if (models == "eara2020"): data = xr.open_dataset(get_data_vc("per_m20_ref.nc")) elif (models == "Initial"): data = xr.open_dataset(get_data_vc("per_m00_ref.nc")) else: raise Exception(f"not supported model {models}") # generate the file to plot to_interp_data = data[parameter].copy() to_interp_data.data[to_interp_data.data > 9e6] = np.nan grd_topo = pygmt.datasets.load_earth_relief(resolution="02m", region=[70, 170, 0, 70]) deps = np.linspace(0, depth, 1001) lons, lats = gmt_project(startlon, startlat, endlon, endlat, x_axis_label) cross_section = model_interp(to_interp_data, lons, lats, deps) # start to plot the figure if (x_axis_label == "lon"): with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection= f"X{0.3*np.abs(startlon-endlon)}i/-{depth/1000*2.7}i", region=f"{startlon}/{endlon}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) cross_section_xarray = xr.DataArray(cross_section, dims=('h', "v"), coords={ 'h': lons, "v": deps }) elif (x_axis_label == "lat"): with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection= f"X{0.3*np.abs(startlat-endlat)}i/-{depth/1000*2.7}i", region=f"{startlat}/{endlat}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) cross_section_xarray = xr.DataArray(cross_section, dims=('h', "v"), coords={ 'h': lats, "v": deps }) elif (x_axis_label == "dist"): # get distance distmax = locations2degrees(startlat, startlon, endlat, endlon) with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*distmax}i/-{depth/1000*2.7}i", region=f"0/{distmax}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) dists = np.linspace(0, distmax, 1001) cross_section_xarray = xr.DataArray(cross_section, dims=('h', "v"), coords={ 'h': dists, "v": deps }) else: raise Exception("not supported x_axis_label") fig.grdimage(cross_section_xarray.T, cmap=True) for interval in ["+-0.1", "+-0.08", "+-0.06", "+-0.04", "+-0.02"]: fig.grdcontour(cross_section_xarray.T, interval=interval, pen="0.5p,black", cut=300, A=interval + "+f6p+u") for interval in ["+0.02", "+0.04", "+0.06", "+0.08", "+0.1"]: fig.grdcontour(cross_section_xarray.T, interval=interval, pen="0.5p,white", cut=300, A=interval + "+f6p+u") if (threshold != 0): # project the events fo = tempfile.NamedTemporaryFile() # use gmt project to select events with Session() as lib: lib.call_module( module="project", args= f"{gmt_get_data_vc('ehb.txt')} -C{startlon}/{startlat} -E{endlon}/{endlat} -Fxyzpq -W-{threshold}/{threshold} > {fo.name}" ) project_generated = np.loadtxt(fo.name) used_lons = project_generated[:, 0] used_lats = project_generated[:, 1] used_deps = project_generated[:, 3] # used_distances = project_generated[:, 5] used_mags = project_generated[:, 2] used_x = project_generated[:, 4] used_x_small = used_x[used_mags < 6] used_x_large = used_x[used_mags >= 6] used_deps_small = used_deps[used_mags < 6] used_deps_large = used_deps[used_mags >= 6] used_lons_small = used_lons[used_mags < 6] used_lons_large = used_lons[used_mags >= 6] used_lats_small = used_lats[used_mags < 6] used_lats_large = used_lats[used_mags >= 6] if (x_axis_label == "lon"): fig.plot(x=used_lons_small, y=used_deps_small, color="white", style="c0.075c", pen="black") fig.plot(x=used_lons_large, y=used_deps_large, color="red", style="a0.3c", pen="black") elif (x_axis_label == "lat"): fig.plot(x=used_lats_small, y=used_deps_small, color="white", style="c0.075c", pen="black") fig.plot(x=used_lats_large, y=used_deps_large, color="red", style="a0.3c", pen="black") elif (x_axis_label == "dist"): fig.plot(x=used_x_small, y=used_deps_small, color="white", style="c0.075c", pen="black") fig.plot(x=used_x_large, y=used_deps_large, color="red", style="a0.3c", pen="black") fo.close() if (x_axis_label == "lon"): y_410 = np.zeros_like(lons) y_410[:] = 410 fig.plot(x=lons, y=y_410, pen="0.5p,black,dashed") y_650 = np.zeros_like(lons) y_650[:] = 650 fig.plot(x=lons, y=y_650, pen="0.5p,black,dashed") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection= f"X{0.3*np.abs(startlon-endlon)}i/-{depth/1000*2.7}i", region=f"{startlon}/{endlon}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection= f"X{0.3*np.abs(startlon-endlon)}i/-{depth/1000*2.7}i", region=f"{startlon}/{endlon}/0/{depth}", frame=[ "WSen", 'yaf+l"Depth (km)"', 'xaf+l"Longitude (degree)"' ]) fig.colorbar( # justified inside map frame (j) at Top Center (TC) position="JBC+w15c/0.8c+h+o0i/2c", box=False, frame=["a1f", f'"+L@~d@~ln{parameter}(%)"'], scale=100, ) elif (x_axis_label == "lat"): y_410 = np.zeros_like(lats) y_410[:] = 410 fig.plot(x=lats, y=y_410, pen="0.5p,black,dashed") y_650 = np.zeros_like(lats) y_650[:] = 650 fig.plot(x=lats, y=y_650, pen="0.5p,black,dashed") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection= f"X{0.3*np.abs(startlat-endlat)}i/-{depth/1000*2.7}i", region=f"{startlat}/{endlat}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection= f"X{0.3*np.abs(startlat-endlat)}i/-{depth/1000*2.7}i", region=f"{startlat}/{endlat}/0/{depth}", frame=[ "WSen", 'yaf+l"Depth (km)"', 'xaf+l"Latitude (degree)"' ]) fig.colorbar( # justified inside map frame (j) at Top Center (TC) position="JBC+w15c/0.8c+h+o0i/2c", box=False, frame=["a1f", f'"+L@~d@~ln{parameter}(%)"'], scale=100, ) elif (x_axis_label == "dist"): y_410 = np.zeros_like(dists) y_410[:] = 410 fig.plot(x=dists, y=y_410, pen="0.5p,black,dashed") y_650 = np.zeros_like(dists) y_650[:] = 650 fig.plot(x=dists, y=y_650, pen="0.5p,black,dashed") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection=f"X{0.3*distmax}i/-{depth/1000*2.7}i", region=f"0/{distmax}/0/{depth}", frame=["wsen", 'yaf', 'xaf']) with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*distmax}i/-{depth/1000*2.7}i", region=f"0/{distmax}/0/{depth}", frame=[ "WSen", 'yaf+l"Depth (km)"', 'xaf+l"Distance (degree)"' ]) fig.colorbar( # justified inside map frame (j) at Top Center (TC) position="JBC+w15c/0.8c+h+o0i/2c", box=False, frame=["a1f", f'"+L@~d@~ln{parameter}(%)"'], scale=100, ) # *********************** grd_interp_result = topo_interp(grd_topo, lons, lats) if (x_axis_label == "lon"): with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*np.abs(startlon-endlon)}i/1i", region=f"{startlon}/{endlon}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=lons, y=np.zeros_like(lons), pen="black", L="+yb", G="lightblue", Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=lons, y=grd_interp_result, pen="black", L="+yb", G="gray", Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection=f"X{0.3*np.abs(startlon-endlon)}i/1i", region=f"{startlon}/{endlon}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*np.abs(startlon-endlon)}i/1i", region=f"{startlon}/{endlon}/-5000/5000", frame=["Wsen", 'ya2500f+l"Elevation (m)"', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") elif (x_axis_label == "lat"): with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*np.abs(startlat-endlat)}i/1i", region=f"{startlat}/{endlat}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=lats, y=np.zeros_like(lats), pen="black", L="+yb", G="lightblue", Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=lats, y=grd_interp_result, pen="black", L="+yb", G="gray", Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection=f"X{0.3*np.abs(startlat-endlat)}i/1i", region=f"{startlat}/{endlat}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*np.abs(startlat-endlat)}i/1i", region=f"{startlat}/{endlat}/-5000/5000", frame=["wsen", 'ya2500f+l"Elevation (m)"', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") elif (x_axis_label == "dist"): with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*distmax}i/1i", region=f"0/{distmax}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=dists, y=np.zeros_like(dists), pen="black", L="+yb", G="lightblue", Y=f"a{depth/1000*2.7+0.4}i") fig.plot(x=dists, y=grd_interp_result, pen="black", L="+yb", G="gray", Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="inside", MAP_TICK_LENGTH_PRIMARY="10p"): fig.basemap(projection=f"X{0.3*distmax}i/1i", region=f"0/{distmax}/-5000/5000", frame=["wsen", 'ya2500f', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") with pygmt.config(MAP_FRAME_TYPE="plain", MAP_TICK_LENGTH="0p"): fig.basemap(projection=f"X{0.3*distmax}i/1i", region=f"0/{distmax}/-5000/5000", frame=["wsen", 'ya2500f+l"Elevation (m)"', 'xaf'], Y=f"a{depth/1000*2.7+0.4}i") fig.savefig(f"./pyapp/vc/figures/{filename}.png") return f"{filename}.png"
def get_map(reg,df,xml_dict=None): """ Returns a map of the stations parameters ---------- reg: list Coordinates df: DataFrame Contains network,station,location,channel,latitude, longitude xml_dict: dict keys-> path,indicator,filter_indicator path : str xml or dataless file path indicator : str It's the indicator that will be filtered. available indicators: network, station, location_id, channel, latitude, longitude, elevation filter_indicator: list List of strings related to the 'indicator' value that will be filtered. """ fig = pygmt.Figure() proj = 'M6i' fig.grdimage('@earth_relief_01m', region=reg, projection=proj, cmap='etopo1', shading=True,) fig.coast(region=reg, projection=proj, shorelines=True, water='lightblue', rivers= ['1/blue','2/blue'], # land='grey', # water='white', borders='1/1p,black', frame="afg",) if xml_dict != None: df_coords = get_contents(xml_dict["path"], indicator=xml_dict["indicator"], filter_indicator=xml_dict["filter_indicator"] ) colors = xml_dict["colors"] if isinstance(df_coords, pd.DataFrame): networks = df_coords.network.unique() for i,net in enumerate(networks): df2 = df_coords.loc[df_coords['network'] == net] lat = df2['latitude'].to_numpy() lon = df2['longitude'].to_numpy() fig.plot(lon,lat, style='t0.15i', color=colors[i], label=net, ) if df is not None: if isinstance(df, pd.DataFrame): stations = df.station.unique() for i,sta in enumerate(stations): df3 = df.loc[df['station'] == sta] lat = df3['latitude'].to_numpy() lon = df3['longitude'].to_numpy() colors = df3['color'].to_numpy() fig.plot(lon,lat, style='t0.15i', color=colors[0], label=sta, ) if (df is not None) or (xml_dict != None): fig.legend() fig.shift_origin(xshift='0i',yshift='0i') # Shift for next call proj = 'G-70/0/2.0i' fig.grdimage( '@earth_relief_10m', region='g', projection=proj, cmap='globe', shading=True, ) fig.coast( region='g', projection=proj, shorelines=True, water='white', borders='1/1p,black', land='grey', frame=True, ) x_reg = [reg[0], reg[1], reg[1], reg[0], reg[0]] y_reg = [reg[2], reg[2], reg[3], reg[3], reg[2]] fig.plot(x_reg,y_reg, pen="2p,red") return fig