def test_config(): """ Test if config works globally and locally. """ fig = Figure() # Change global settings of current figure config(FONT_ANNOT_PRIMARY="blue") fig.basemap( region="0/10/0/10", projection="X10c/10c", frame=["af", '+t"Blue Annotation"'] ) with config(FONT_LABEL="red", FONT_ANNOT_PRIMARY="red"): fig.basemap( region="0/10/0/10", projection="X10c/10c", frame=['xaf+l"red label"', "yaf", '+t"red annotation"'], X="15c", ) fig.basemap( region="0/10/0/10", projection="X10c/10c", frame=["af", '+t"Blue Annotation"'], X="15c", ) # Revert to default settings in current figure config(FONT_ANNOT_PRIMARY="black") return fig
def test_config_font_one(): """ Test that setting `FONT` config changes all `FONT_*` settings except `FONT_LOGO`. Specifically, this test only checks that `FONT_ANNOT_PRIMARY`, `FONT_ANNOT_SECONDARY`, `FONT_LABEL`, and `FONT_TITLE` are modified. """ fig_ref = Figure() with config( FONT_ANNOT_PRIMARY="8p,red", FONT_ANNOT_SECONDARY="8p,red", FONT_LABEL="8p,red", FONT_TITLE="8p,red", ): fig_ref.basemap(R="0/9/0/9", J="C3/3/9c", Tm="jTL+w4c+d4.5+l") fig_ref.basemap(Tm="jBR+w5c+d-4.5+l") fig_test = Figure() with config(FONT="8p,red"): fig_test.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", compass="******") fig_test.basemap(compass="******") return fig_ref, fig_test
def test_config_font_annot(): """ Test that setting `FONT_ANNOT` config changes both `FONT_ANNOT_PRIMARY` and `FONT_ANNOT_SECONDARY`. """ fig_ref = Figure() with config(FONT_ANNOT_PRIMARY="6p,red", FONT_ANNOT_SECONDARY="6p,red"): fig_ref.basemap(R="0/9/0/9", J="C3/3/9c", Tm="jTL+w4c+d4.5") fig_ref.basemap(compass="******") fig_test = Figure() with config(FONT_ANNOT="6p,red"): fig_test.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", compass="******") fig_test.basemap(compass="******") return fig_ref, fig_test
def test_config_font_annot(): """ Test that setting `FONT_ANNOT` config changes both `FONT_ANNOT_PRIMARY` and `FONT_ANNOT_SECONDARY`. """ fig = Figure() with config(FONT_ANNOT="6p,red"): fig.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", T="mjTL+w4c+d4.5") fig.basemap(T="mjBR+w5c+d-4.5") return fig
def test_config_font_one(): """ Test that setting `FONT` config changes all `FONT_*` settings except `FONT_LOGO`. Specifically, this test only checks that `FONT_ANNOT_PRIMARY`, `FONT_ANNOT_SECONDARY`, `FONT_LABEL`, and `FONT_TITLE` are modified. """ fig = Figure() with config(FONT="8p,red"): fig.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", T="mjTL+w4c+d4.5+l") fig.basemap(T="mjBR+w5c+d-4.5+l") return fig
def test_config_font_annot(): """ Test that setting FONT_ANNOT config changes both FONT_ANNOT_PRIMARY and FONT_ANNOT_SECONDARY. """ fig = Figure() with config(FONT_ANNOT="6p,red"): fig.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", compass="******") fig.basemap(compass="******") return fig
def test_config_font_one(): """ Test that setting FONT config changes all FONT_* settings except FONT_LOGO. Specifically, this test only checks that FONT_ANNOT_PRIMARY, FONT_ANNOT_SECONDARY, FONT_LABEL, and FONT_TITLE are modified. """ fig = Figure() with config(FONT="8p,red"): fig.basemap(region=[0, 9, 0, 9], projection="C3/3/9c", compass="******") fig.basemap(compass="******") return fig
def test_config_map_grid_cross_size(): """ Test that setting `MAP_GRID_CROSS_SIZE` config changes both `MAP_GRID_CROSS_SIZE_PRIMARY` and `MAP_GRID_CROSS_SIZE_SECONDARY`. """ fig = Figure() with config(MAP_GRID_CROSS_SIZE="3p"): fig.basemap( region=["2020-1-24T21:00", "2020-1-25T00:00", 0, 1], projection="X6c/2c", frame=["pa1Hg", "sa45mg45m", "NWse"], ) fig.basemap(frame=["pa1Hg", "sa45mg45m", "nwSE"], Y=-3) return fig
def test_config_map_tick_pen(): """ Test that setting `MAP_TICK_PEN` config changes both `MAP_TICK_PEN_PRIMARY` and `MAP_TICK_PEN_SECONDARY`. """ fig = Figure() with config(MAP_TICK_PEN="thick,red"): fig.basemap( region=["2020-1-24T21:00", "2020-1-25T00:00", 0, 1], projection="X6c/2c", frame=["pa1Hg", "sa45mg45m", "NWse"], ) fig.basemap(frame=["pa1Hg", "sa45mg45m", "nwSE"], Y=-3) return fig
def test_config_format_time_map(): """ Test that setting `FORMAT_TIME_MAP` config changes both `FORMAT_TIME_PRIMARY_MAP` and `FORMAT_TIME_SECONDARY_MAP`. """ fig = Figure() with config(FORMAT_TIME_MAP="abbreviation"): fig.basemap( region=["2020-1-24T", "2020-1-27T", 0, 1], projection="X6c/1c", frame=["pa1K", "sa1K", "NWse"], ) fig.basemap(frame=["pa1K", "sa1K", "nwSE"]) return fig
def test_config_map_annot_offset(): """ Test that setting `MAP_ANNOT_OFFSET` config changes both `MAP_ANNOT_OFFSET_PRIMARY` and `MAP_ANNOT_OFFSET_SECONDARY`. """ fig = Figure() with config(MAP_ANNOT_OFFSET="15p"): fig.basemap( region=["2020-1-24T", "2020-1-27T", 0, 1], projection="X6c/1c", frame=["pa1d", "sa1d", "NWse"], ) fig.basemap(frame=["pa1d", "sa1d", "nwSE"]) return fig
def test_config_map_grid_pen(): """ Test that setting MAP_GRID_PEN config changes both MAP_GRID_PEN_PRIMARY and MAP_GRID_PEN_SECONDARY. """ fig = Figure() with config(MAP_GRID_PEN="thick,red"): fig.basemap( region=["2020-1-24T21:00", "2020-1-25T00:00", 0, 1], projection="X6c/2c", frame=["pa1Hg", "sa45mg45m", "NWse"], verbose="e", ) fig.basemap(frame=["pa1Hg", "sa45mg45m", "nwSE"], yshift=-3, verbose="e") return fig
def test_config_map_tick_length(): """ Test that setting MAP_TICK_LENGTH config changes both MAP_TICK_LENGTH_PRIMARY and MAP_TICK_LENGTH_SECONDARY. """ fig = Figure() with config(MAP_TICK_LENGTH="5p"): fig.basemap( region=["2020-1-24T21:00", "2020-1-25T00:00", 0, 1], projection="X6c/2c", frame=["pa1Hg", "sa45mg45m", "NWse"], verbose="e", ) fig.basemap(frame=["pa1Hg", "sa45mg45m", "nwSE"], yshift=-3, verbose="e") return fig
def test_config_format_date_map(): """ Test that setting FORMAT_DATE_MAP config changes how the output date string is plotted. Note the space in 'o dd', this acts as a regression test for https://github.com/GenericMappingTools/pygmt/issues/247. """ fig = Figure() with config(FORMAT_DATE_MAP="o dd"): fig.basemap( region=["1969-7-21T", "1969-7-23T", 0, 1], projection="X2.5c/0.1c", frame=["sxa1D", "S"], ) return fig
# sphinx_gallery_thumbnail_number = 3 fig = pygmt.Figure() fig.basemap(region=[115, 119.5, 4, 7.5], projection="M10c", frame=True) fig.coast(land="black", water="skyblue") fig.show() #%% # 设置全局参数 # ------------------- fig = pygmt.Figure() # 全局参数影响接下来所有的命令 pygmt.config(MAP_FRAME_TYPE="plain") pygmt.config(FORMAT_GEO_MAP="ddd.xx") fig.basemap(region=[115, 119.5, 4, 7.5], projection="M10c", frame=True) fig.coast(land="black", water="skyblue") fig.show() #%% # 设置临时参数 # ----------------- fig = pygmt.Figure() # 仅对当前命令有效,将边框设置为 fancy+ with pygmt.config(MAP_FRAME_TYPE="fancy+"):
fig = pygmt.Figure() # Plot the common X axes # The bottom axis (S) is plotted with annotations and tick marks # The top axis (t) is plotted without annotations and tick marks # The left and right axes are not drawn fig.basemap(region=[0, 10, 0, 10], projection="X15c/15c", frame=["St", "xaf+lx"]) # Plot the Y axis for y1 data # The left axis (W) is plotted with blue annotations, ticks, and label with pygmt.config( MAP_FRAME_PEN="blue", MAP_TICK_PEN="blue", FONT_ANNOT_PRIMARY="blue", FONT_LABEL="blue", ): fig.basemap(frame=["W", "yaf+ly1"]) # Plot the line for y1 data fig.plot(x=x, y=y1, pen="1p,blue") # Plot points for y1 data fig.plot(x=x, y=y1, style="c0.2c", color="blue", label="y1") # Plot the Y axis for y2 data # The right axis (E) is plotted with red annotations, ticks, and label with pygmt.config( MAP_FRAME_PEN="red", MAP_TICK_PEN="red", FONT_ANNOT_PRIMARY="red",
df_max = df_th.query(expr="x == @max_h_X.x & y == @max_h_X.y").sort_values( by="t") track1, track2 = df_max.track1_track2.iloc[0].split("x") print( f"{round(max_h_X.h_X, 2)} metres height change at {max_h_X.x}, {max_h_X.y}" ) plotregion = np.array([ df_max.t.min(), df_max.t.max(), *pygmt.info(table=df_max[["h"]], spacing=2.5)[:2] ]) plotregion += np.array( [-pd.Timedelta(2, unit="W"), +pd.Timedelta(2, unit="W"), 0, 0]) fig = pygmt.Figure() with pygmt.config(FONT_ANNOT_PRIMARY="9p", FORMAT_TIME_PRIMARY_MAP="abbreviated", FORMAT_DATE_MAP="o"): fig.basemap( projection="X12c/8c", region=plotregion, frame=[ f'WSne+t"Max elevation change over time at {region.name}"', "pxa1Of1o+lDate", # primary time axis, 1 mOnth annotation and minor axis "sx1Y", # secondary time axis, 1 Year intervals 'yaf+l"Elevation at crossover (m)"', ], ) fig.text( text=f"Track {track1} and {track2} crossover", position="TC", offset="jTC0c/0.2c",
fig.plot(x=xpoints, y=ypoints, style="t0.3c", color="purple", no_clip=False, pen="black") fig.show() #%% # **-JP:** 极坐标线性投影 # ---------------------------- fig = pygmt.Figure() # 配置参数 pygmt.config(FORMAT_GEO_MAP="+D") pygmt.config(FONT_TITLE="14p,1,red") # 移动原点。绘制第一张图 fig.shift_origin(yshift="10c") # 绘制极坐标数据,默认为 角度 和 半径,默认情况下,角度是指相当于东方向逆时针旋转的角度 fig.basemap(region="0/360/0/1", projection="P5c", frame=['+t"-JP5c -R0/360/0/1"', "xa45f"]) fig.shift_origin(xshift="8c") # 加上 +a 则表明输入数据是相对于北方向顺时针旋转的角度(地理学中的方位角) fig.basemap(region="0/360/0/1", projection="P5c+a", frame=['+t"-JP5c+a -R0/90/0/1"', "xa45f", "ya0.2"])
fig = pygmt.Figure() # Vector 1 with default unit as cm fig.plot( region=[0, 10, 0, 10], projection="X5i/5i", frame="ag", x=2, y=8, style="v1c+e", direction=[[0], [3]], pen="2p", color="red3", ) # Vector 2 after changing default unit to inch with pygmt.config(PROJ_LENGTH_UNIT="i"): fig.plot( x=2, y=7, direction=[[0], [3]], style="v1c+e", pen="2p", color="red3", ) fig.show() ######################################################################################## # Vectors can also be plotted by including all the information # about a vector in a single list. However, this requires creating # a 2D list or numpy array containing all vectors. # Each vector list contains the information structured as:
# Plot moment tensors which should be in a file in the psmeca format from GCMT # lon lat depth mrr mtt mpp mrt mrp mtp iexp name if moment_tensors and mt_fid: # Make the colormap to shade MTs by depth depths = np.loadtxt(mt_fid, usecols=2, dtype=float) makecpt(cmap=mt_cmap, series=[min(depths), max(depths), 1]) mts = fig.meca(mt_fid, scale=mt_scale, convention="mt", component="dc", C=True, verbose=True, L="1p/black") if mt_colorbar: fig.colorbar(position="n.95/.825+w-2c/.45c", frame='af+l"depth [km]"') # Scalebar, need to use config to set the pen thickness of the scale with config(MAP_TICK_PEN_PRIMARY=1.5): fig.basemap(region=region, projection=projection, #frame=["WSne", "gfa"], map_scale=map_scale) # Landmark text fig.text(textfiles=landmarks_fid) # Plot the whole of Alaska as an inset to give context if inset: with fig.inset(position="n0/.75+w5c/4c", margin=0): # Plot the whole of Alaska as the inset fig.coast(region=[-170, -135, 53, 72], projection="L-150/62/63/64/3.5c", land="gray", water="white", shorelines="0p,black", frame=False, resolution="h", area_thresh=100) # !!! THIS DOESNT WORK Put a box in the inset around Northern Alaska
import pygmt # Define region of interest around Yosemite valley region = [-119.825, -119.4, 37.6, 37.825] # Load sample grid (3 arc second global relief) in target area grid = pygmt.datasets.load_earth_relief(resolution="03s", region=region) # calculate the reflection of a light source projecting from west to east # (azimuth of 270 degrees) and at a latitude of 30 degrees from the horizon dgrid = pygmt.grdgradient(grid=grid, radiance=[270, 30]) fig = pygmt.Figure() # define figure configuration pygmt.config(FORMAT_GEO_MAP="ddd.x", MAP_FRAME_TYPE="plain") # --------------- plotting the original Data Elevation Model ----------- pygmt.makecpt(cmap="gray", series=[200, 4000, 10]) fig.grdimage( grid=grid, projection="M12c", frame=['WSrt+t"Original Data Elevation Model"', "xa0.1", "ya0.1"], cmap=True, ) fig.colorbar(position="JML+o1.4c/0c+w7c/0.5c", frame=["xa1000f500+lElevation", "y+lm"]) # --------------- plotting the hillshade map -----------
import pygmt ############################################################################### # Basic map annotation # -------------------- # # Text annotations can be added to a map using the :meth:`pygmt.Figure.text` # method of the :class:`pygmt.Figure` class. # # Here we create a simple map and add an annotation using the ``text``, ``x``, # and ``y`` parameters to specify the annotation text and position in the # projection frame. ``text`` accepts *str* types, while ``x``, and ``y`` # accepts either *int* or *float* numbers, or a list/array of numbers. fig = pygmt.Figure() with pygmt.config(MAP_FRAME_TYPE="plain"): fig.basemap(region=[108, 120, -5, 8], projection="M20c", frame="a") fig.coast(land="black", water="skyblue") # Plot text annotations using a single element fig.text(text="SOUTH CHINA SEA", x=112, y=6) # Plot text annotations using lists of elements fig.text(text=["CELEBES SEA", "JAVA SEA"], x=[119, 112], y=[3.25, -4.6]) fig.show() ############################################################################### # Changing font style # ------------------- # The size, family/weight, and color of an annotation can be specified using
to the maximum value of the r axis when the r axis is reversed. - Append *radius* to set the maximum value of the r axis. - **+z**: indicates that the r axis is marked as depth instead of radius (e.g. *r = radius - z*). - Append **p** to set radius to the current earth radius. - Append *radius* to set the value of the radius. """ import pygmt fig = pygmt.Figure() pygmt.config(FONT_TITLE="14p,Helvetica,black", FORMAT_GEO_MAP="+D") # ============ fig.basemap( # set map limits to theta_min = 0, theta_max = 360, radius_min = 0, radius_max = 1 region=[0, 360, 0, 1], # set map width to 5 cm projection="P5c", # set the frame and color frame=["xa45f", "+gbisque"], ) fig.text(position="TC", text="projection='P5c'", offset="0/2.0c", no_clip=True) fig.text(position="TC", text="region=[0, 360, 0, 1]",
def plot_crossovers( df: pd.DataFrame, regionname: str, elev_var: str = "h", time_var: str = "t", track_var: str = "track1_track2", spacing: float = 2.5, elev_filter: float = 1.0, ) -> pygmt.Figure: """ Plot to show how elevation is changing at many crossover points over time. Uses PyGMT to produce the figure. The input table should look something like below (more columns can be present too). | track1_track2 | h | t | |------------------|-----|---------------------| | 0111_pt1x0222pt2 | 111 | 2020-01-01T01:12:34 | | 0222_pt2x0333pt3 | 110 | 2020-04-01T12:23:45 | | 0333_pt3x0111pt1 | 101 | 2020-07-01T23:34:56 | which will produce a plot similar to the following: ICESat-2 Crossover Elevations over Time at Some Ice Stream ^ | -a---a---a---a | -a---a---a---a---a-/ -b---b---b -a- 0111_pt1x0222pt2 Elev | -b---b---b---b---b---b-/ -c- -b- 0222_pt2x0333pt3 | -c---c---c---c---c---c----/ \-c---c -c- 0333_pt3x0111pt1 |___________________________________________> Date Parameters ---------- df : pandas.DataFrame A table containing the ICESat-2 track data from multiple cycles. It should ideally have columns called 'h', 't', and 'track1_track2'. regionname : str A descriptive placename for the data (e.g. Some Ice Stream), to be used in the figure's main title. elev_var : str The elevation column name to use from the table data, plotted on the vertical y-axis. Default is 'h'. time_var : str The time-dimension column name to use from the table data, plotted on the horizontal x-axis. Default is 't'. track_var : str The track column name to use from the table data, containing variables in the form of track1xtrack2 (note that 'x' is a hardcoded delimiter), e.g. 0111_pt1x0222pt2. Default is 'track1_track2'. spacing : str or float Provide as a 'dy' increment, this is passed on to `pygmt.info` and used to round up and down the y axis (elev_var) limits for a nicer plot frame. Default is 2.5. elev_filter : float Minimum elevation change required for the crossover point to show up on the plot. Default is 1.0 (metres). Returns ------- fig : pygmt.Figure A pygmt Figure instance containing the crossover plot which can be viewed using fig.show() or saved to a file using fig.savefig() """ fig = pygmt.Figure() # Setup map frame, title, axis annotations, etc with pygmt.config( FONT_ANNOT_PRIMARY="9p", FORMAT_TIME_PRIMARY_MAP="abbreviated", FORMAT_DATE_MAP="o", ): # Get plot region, spaced out into nice intervals # Note that passing time columns into pygmt.info doesn't work well yet, # see https://github.com/GenericMappingTools/pygmt/issues/597 plotregion = np.array( [ df[time_var].min() - pd.Timedelta(1, unit="W"), df[time_var].max() + pd.Timedelta(1, unit="W"), *pygmt.info(table=df[[elev_var]], spacing=spacing)[:2], ] ) # pygmt.info(table=df[[time_var, elev_var]], spacing=f"1W/{spacing}", f="0T") fig.basemap( projection="X12c/12c", region=plotregion, frame=[ rf'WSne+t"ICESat-2 Crossover Elevations over Time at {regionname}"', "pxa1Of1o+lDate", # primary time axis, 1 mOnth annotation and minor axis "sx1Y", # secondary time axis, 1 Year intervals 'yaf+l"Elevation at crossover (m)"', ], ) crossovers = df.groupby(by=track_var) pygmt.makecpt(cmap="categorical", series=[1, len(crossovers) + 1, 1]) for i, ((track1_track2), indexes) in enumerate( tqdm.tqdm(crossovers.indices.items()) ): df_ = df.loc[indexes].sort_values(by=time_var) # plot only > 1 metre height change if df_[elev_var].max() - df_[elev_var].min() > elev_filter: track1, track2 = track1_track2.split("x") fig.plot( x=df_[time_var], y=df_[elev_var], Z=i, style="c0.1c", cmap=True, pen="thin+z", label=f'"Track {track1} {track2}"', ) # Plot line connecting points fig.plot( x=df_[time_var], y=df_[elev_var], Z=i, pen=f"faint,+z,-", cmap=True ) with pygmt.config(FONT_ANNOT_PRIMARY="9p"): fig.legend(S=0.8, position="JTR+jTL+o0.2c", box="+gwhite+p1p") return fig
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"
if bedname == "diff": pygmt.makecpt( cmap="vik+h0", series=pygmt.grdinfo(grid=grid, T="+a0.5+s")[2:-1], ) fig.grdimage( grid=grid, region=pygmt.grdinfo(grid, I="r")[2:-1], cmap=True, projection="X10c/14c", ) if bedname == "diff": fig.colorbar(position="JMR+o1.5c/0c+e", frame=["af", f'y+l"{z_attr.unit}"']) with pygmt.config(FONT_TITLE="14p"): fig.plot( x=transect.x, y=transect.y, color=transect[z_attr.varname], pen="1p", frame=[f'lrbt+t"{title}"'], ) fig.text(x=pointA.x, y=pointA.y, text="A", justify="TR") fig.text(x=pointB.x, y=pointB.y, text="B", justify="BL") # End subplot subplot(args="end") fig.colorbar( position="JBC",
tcolor = tcolor_str.split(sep='/') if (len(tcolor) != 3): eprint("Format of color is invalid! (<0~255>/<0~255>/<0~255>)") sys.exit(1) for i in range(0, len(tcolor)): tcolor[i] = float(tcolor[i]) if not ((0 <= tcolor[0] <= 255) and (0 <= tcolor[1] <= 255) and (0 <= tcolor[2] <= 255)): eprint("Format of color is invalid! (<0~255>/<0~255>/<0~255>)") sys.exit(1) ##### main program pygmt.config(FONT_TITLE=12) pygmt.config(MAP_TITLE_OFFSET='-1c') fig = pygmt.Figure() # generate a basemap near Washington state showing coastlines, land, and water fig.basemap(region=[-1, 1, -1, 1], projection="M6c", frame=[f'+n+t"{title}"']) # store focal mechanisms parameters in a dict #focal_mechanism = dict(strike=330, dip=30, rake=90, magnitude=3) focal_mechanism = dict(strike=strike, dip=dip, rake=rake, magnitude=3) # pass the focal mechanism data to meca in addition to the scale and event location fig.meca(focal_mechanism, scale="6c", longitude=0, latitude=0,
# ``"sxa1Of1D"``. This string modifies the secondary # labeling (**s**) of the x-axis (**x**). Specifically, # it sets the main annotation and major tick spacing interval # to one month (**a1O**) (capital letter o, not zero). Additionally, # it sets the minor tick spacing interval to 1 day (**f1D**). # The labeling of this axis can be modified by setting # :gmt-term:`FORMAT_DATE_MAP` to 'o' to use the month's # name instead of its number. More information about configuring # date formats can be found on the # :gmt-term:`official GMT documentation page <FORMAT_DATE_MAP>`. x = pd.date_range("2013-05-02", periods=10, freq="2D") y = [4, 5, 6, 8, 9, 5, 8, 9, 4, 2] fig = pygmt.Figure() with pygmt.config(FORMAT_DATE_MAP="o"): fig.plot( projection="X15c/10c", region=[datetime.datetime(2013, 5, 1), datetime.datetime(2013, 5, 25), 0, 10], frame=["WS", "sxa1Of1D", "pxa5d", "sy+lLength", "pya1+ucm"], x=x, y=y, style="c0.4c", pen="1p", color="green3", ) fig.show() ######################################################################################## # The same concept shown above can be applied to smaller
import pygmt import numpy as np with pygmt.config(PS_MEDIA='9.5ix21.5i', PS_PAGE_ORIENTATION='landscape', PROJ_LENGTH_UNIT='inch', MAP_FRAME_TYPE='plain', MAP_TICK_LENGTH='0.0c', MAP_FRAME_PEN='2p', FONT_ANNOT_PRIMARY='12p,Helvetica,black', FONT_HEADING='18p,Helvetica,black', FONT_LABEL='10p,Helvetica,black'): fig = pygmt.Figure() # First Lune fig.basemap(projection='H0/2.8i', region='-30/30/-90/90', frame=['xa10f5g10','ya10f5g10','wesn+g200'], xshift='0.5', yshift='0.5') x,y = np.genfromtxt('../dfiles/sourcetype_patch_01.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, color='120', close='+x0') x,y = np.genfromtxt('../dfiles/sourcetype_patch_02.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, color='255', close='+x0') fig.basemap(projection='H0/2.8i', region='-30/30/-90/90', frame=['xa10f5g10','ya10f5g10','wesn']) x,y = np.genfromtxt('../dfiles/sourcetype_arc_01.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, pen='3p,160/32/240') x,y = np.genfromtxt('../dfiles/sourcetype_arc_02.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, pen='3p,255/0/0') x,y = np.genfromtxt('../dfiles/sourcetype_arc_03.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, pen='3p,30/144/255') x,y = np.genfromtxt('../dfiles/sourcetype_arc_04.dat', unpack=True, usecols=(0,1)) fig.plot(x=x, y=y, pen='3p,30/144/255') x,y = np.genfromtxt('../dfiles/sourcetype_arc_06.dat', unpack=True, usecols=(0,1))
import pygmt with pygmt.config(PS_MEDIA='3.2ix7.7i', PS_PAGE_ORIENTATION='portrait', PROJ_LENGTH_UNIT='inch', MAP_FRAME_TYPE='plain', MAP_TICK_LENGTH='0.0c', MAP_FRAME_PEN='2p', MAP_TICK_PEN='2p'): fig = pygmt.Figure() fig.basemap(projection='X2.25i/6.72i', region='-30/30/-90/90', frame=['xa10f5g10', 'ya10f5g10', 'wesn+g200'], xshift='0.5', yshift='0.5') fig.meca(spec='beachballs_ipts1_iref1_lune_psmeca', scale='0.45i', convention='mt', no_clip=True, G='255/0/0', L='0.5p,0/0/0', W='0.5p,0/0/0') fig.savefig('lune_pygmt.pdf')