Skip to content

Commit 4a789d9

Browse files
authored
Modified and included arguments for spatial plotting functions and filled doc strings with missing variables (#136)
- Basemap plotting: Added fontsize arg for grid labels. Added figsize arg. Added manual Zoom Tile level, in case a greater or lower resolution of the map is desired. - Catalog plotting: Included modified basemap options. Added legend title, framealpha, label fontsize, title fontsize as arguments. Check if given mag_ticks args is list, array or tuple. - Basemap plotting: Added title_size into correct function args. Added colormap title and ticks fontsize as argument
1 parent e0d0065 commit 4a789d9

File tree

1 file changed

+66
-32
lines changed

1 file changed

+66
-32
lines changed

csep/utils/plots.py

Lines changed: 66 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -553,24 +553,31 @@ def get_hist(x, mws, normed=True):
553553
if show:
554554
pyplot.show()
555555

556-
def plot_basemap(basemap, extent, ax=None, coastline=True, borders=False, linecolor='black', linewidth=True,
557-
grid=False, grid_labels=False, set_global=False, show=False, projection=ccrs.PlateCarree(), apprx=False,
558-
central_latitude=0.0):
556+
def plot_basemap(basemap, extent, ax=None, figsize=None, coastline=True, borders=False, tile_scaling='auto',
557+
set_global=False, projection=ccrs.PlateCarree(), apprx=False, central_latitude=0.0,
558+
linecolor='black', linewidth=True,
559+
grid=False, grid_labels=False, grid_fontsize=None,
560+
show=False):
559561
""" Wrapper function for multiple cartopy base plots, including access to standard raster webservices
560562
561563
Args:
562564
basemap (str): Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link (see examples in :func:`csep.utils.plots._get_basemap`. Default is None
563565
extent (list): [lon_min, lon_max, lat_min, lat_max]
564-
show (bool): Flag if the figure is displayed
565-
set_global (bool): Display the complete globe as basemap
566+
ax (:class:`matplotlib.pyplot.ax`): Previously defined ax object
567+
figsize (tuple): If no ax is provided, a tuple of floats can be provided to define figure size
566568
coastline (str): Flag to plot coastline. default True,
567569
borders (bool): Flag to plot country borders. default False,
568-
linewidth (float): Line width of borders and coast lines. default 1.5,
570+
tile_scaling (str/int): Zoom level (1-12) of the basemap tiles. If 'auto', is automatically derived from extent
571+
set_global (bool): Display the complete globe as basemap
572+
projection (:class:`cartopy.crs.Projection`): Projection to be used in the basemap
573+
apprx (bool): If true, approximates transformation by setting aspect ratio of axes based on middle latitude
574+
central_latitude (float): average latitude from plotting region
569575
linecolor (str): Color of borders and coast lines. default 'black',
576+
linewidth (float): Line width of borders and coast lines. default 1.5,
570577
grid (bool): Draws a grid in the basemap
571578
grid_labels (bool): Annotate grid values
572-
apprx (bool): If true, approximates transformation by setting aspect ratio of axes based on middle latitude
573-
central_latitude (float): average latitude from plotting region
579+
grid_fontsize (float): Font size of the grid x and y labels
580+
show (bool): Flag if the figure is displayed
574581
575582
Returns:
576583
:class:`matplotlib.pyplot.ax` object
@@ -579,14 +586,14 @@ def plot_basemap(basemap, extent, ax=None, coastline=True, borders=False, linec
579586
if ax is None:
580587
if apprx:
581588
projection = ccrs.PlateCarree()
582-
fig = pyplot.figure()
589+
fig = pyplot.figure(figsize=figsize)
583590
ax = fig.add_subplot(111, projection=projection)
584591
# Set plot aspect according to local longitude-latitude ratio in metric units
585592
# (only compatible with plain PlateCarree "projection")
586593
LATKM = 110.574 # length of a ° of latitude [km]; constant --> ignores Earth's flattening
587594
ax.set_aspect(LATKM / (111.320 * numpy.cos(numpy.deg2rad(central_latitude))))
588595
else:
589-
fig = pyplot.figure()
596+
fig = pyplot.figure(figsize=figsize)
590597
ax = fig.add_subplot(111, projection=projection)
591598

592599
if set_global:
@@ -600,7 +607,10 @@ def plot_basemap(basemap, extent, ax=None, coastline=True, borders=False, linec
600607
tile_autoscaler = cartopy.feature.AdaptiveScaler(5, ((6, 50), (7, 15)))
601608
tiles = None
602609
# Set tile depth
603-
tile_depth = 4 if set_global else tile_autoscaler.scale_from_extent(extent)
610+
if tile_scaling == 'auto':
611+
tile_depth = 4 if set_global else tile_autoscaler.scale_from_extent(extent)
612+
else:
613+
tile_depth = tile_scaling
604614
if coastline:
605615
ax.coastlines(color=linecolor, linewidth=linewidth)
606616
if borders:
@@ -621,6 +631,8 @@ def plot_basemap(basemap, extent, ax=None, coastline=True, borders=False, linec
621631
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
622632
gl.right_labels = False
623633
gl.top_labels = False
634+
gl.xlabel_style['fontsize'] = grid_fontsize
635+
gl.ylabel_style['fontsize'] = grid_fontsize
624636
gl.xformatter = LONGITUDE_FORMATTER
625637
gl.yformatter = LATITUDE_FORMATTER
626638

@@ -646,22 +658,25 @@ def plot_catalog(catalog, ax=None, show=False, extent=None, set_global=False, pl
646658
- :filename: :class:`str` - File to save figure. default None
647659
- :projection: :class:`cartopy.crs.Projection` - default :class:`cartopy.crs.PlateCarree`. Note: this can be
648660
'fast' to apply an approximate transformation of axes.
661+
- :basemap: :class:`str`/:class:`None`. Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link. Default is None
662+
- :coastline: :class:`bool` - Flag to plot coastline. default True,
649663
- :grid: :class:`bool` - default True
650664
- :grid_labels: :class:`bool` - default True
665+
- :grid_fontsize: :class:`float` - default 10.0
651666
- :marker: :class:`str` - Marker type
652667
- :markersize: :class:`float` - Constant size for all earthquakes
653668
- :markercolor: :class:`str` - Color for all earthquakes
654-
- :basemap: :class:`str`/:class:`None`. Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link. Default is None
655-
- :coastline: :class:`bool` - Flag to plot coastline. default True,
656669
- :borders: :class:`bool` - Flag to plot country borders. default False,
657-
- :linewidth: :class:`float` - Line width of borders and coast lines. default 1.5,
658-
- :linecolor: :class:`str` - Color of borders and coast lines. default 'black',
670+
- :region_border: :class:`bool` - Flag to plot the catalog region border. default True,
659671
- :alpha: :class:`float` - Transparency for the earthquakes scatter
660672
- :mag_scale: :class:`float` - Scaling of the scatter
661673
- :legend: :class:`bool` - Flag to display the legend box
662674
- :legend_loc: :class:`int`/:class:`str` - Position of the legend
663675
- :mag_ticks: :class:`list` - Ticks to display in the legend
664676
- :labelspacing: :class:`int` - Separation between legend ticks
677+
- :tile_scaling: :class:`str`/:class:`int`. Zoom level (1-12) of the basemap tiles. If 'auto', is automatically derived from extent
678+
- :linewidth: :class:`float` - Line width of borders and coast lines. default 1.5,
679+
- :linecolor: :class:`str` - Color of borders and coast lines. default 'black',
665680
666681
Returns:
667682
:class:`matplotlib.pyplot.ax` object
@@ -682,17 +697,23 @@ def plot_catalog(catalog, ax=None, show=False, extent=None, set_global=False, pl
682697
alpha = plot_args.get('alpha', 1)
683698
mag_scale = plot_args.get('mag_scale', 1)
684699
legend = plot_args.get('legend', False)
700+
legend_title = plot_args.get('legend_title', r"Magnitudes")
685701
legend_loc = plot_args.get('legend_loc', 1)
702+
legend_framealpha = plot_args.get('legend_framealpha', None)
703+
legend_fontsize = plot_args.get('legend_fontsize', None)
704+
legend_titlesize = plot_args.get('legend_titlesize', None)
686705
mag_ticks = plot_args.get('mag_ticks', False)
687706
labelspacing = plot_args.get('labelspacing', 1)
688707
region_border = plot_args.get('region_border', True)
689708
# cartopy properties
690709
projection = plot_args.get('projection', ccrs.PlateCarree(central_longitude=0.0))
691-
grid = plot_args.get('grid', True)
692-
grid_labels = plot_args.get('grid_labels', False)
693710
basemap = plot_args.get('basemap', None)
694711
coastline = plot_args.get('coastline', True)
712+
grid = plot_args.get('grid', True)
713+
grid_labels = plot_args.get('grid_labels', False)
714+
grid_fontsize = plot_args.get('grid_fontsize', False)
695715
borders = plot_args.get('borders', False)
716+
tile_scaling = plot_args.get('tile_scaling', 'auto')
696717
linewidth = plot_args.get('linewidth', True)
697718
linecolor = plot_args.get('linecolor', 'black')
698719

@@ -728,7 +749,7 @@ def plot_catalog(catalog, ax=None, show=False, extent=None, set_global=False, pl
728749
ax.set_extent(extents=extent, crs=ccrs.PlateCarree()) # Defined extent always in lat/lon
729750

730751
# Basemap plotting
731-
ax = plot_basemap(basemap, extent, ax=ax, coastline=coastline, borders=borders,
752+
ax = plot_basemap(basemap, extent, ax=ax, coastline=coastline, borders=borders, tile_scaling=tile_scaling,
732753
linecolor=linecolor, linewidth=linewidth, projection=projection, apprx=apprx,
733754
central_latitude=central_latitude)
734755

@@ -751,18 +772,17 @@ def size_map(markersize, values, scale):
751772

752773
# Legend
753774
if legend:
754-
if not mag_ticks:
755-
mag_ticks = numpy.linspace(mw_range[0], mw_range[1], 4)
756-
else:
775+
if isinstance(mag_ticks, (tuple, list, numpy.ndarray)):
757776
if not numpy.all([ i >= mw_range[0] and i <= mw_range[1] for i in mag_ticks]):
758777
print("Magnitude ticks do not lie within the catalog magnitude range")
759-
778+
elif mag_ticks is False:
779+
mag_ticks = numpy.linspace(mw_range[0], mw_range[1], 4)
760780
handles, labels = scatter.legend_elements(prop="sizes",
761781
num=list(size_map(markersize, mag_ticks, mag_scale)),
762782
alpha=0.3)
763783
ax.legend(handles, numpy.round(mag_ticks, 1),
764-
loc=legend_loc, title=r"Magnitudes", title_fontsize=16,
765-
labelspacing=labelspacing, handletextpad=5, framealpha=False)
784+
loc=legend_loc, title=legend_title, fontsize=legend_fontsize, title_fontsize=legend_titlesize,
785+
labelspacing=labelspacing, handletextpad=5, framealpha=legend_framealpha)
766786

767787
if region_border:
768788
try:
@@ -777,6 +797,8 @@ def size_map(markersize, values, scale):
777797
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
778798
gl.right_labels = False
779799
gl.top_labels = False
800+
gl.xlabel_style['fontsize'] = grid_fontsize
801+
gl.ylabel_style['fontsize'] = grid_fontsize
780802
gl.xformatter = LONGITUDE_FORMATTER
781803
gl.yformatter = LATITUDE_FORMATTER
782804

@@ -808,14 +830,19 @@ def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_
808830
- :projection: :class:`cartopy.crs.Projection` - default :class:`cartopy.crs.PlateCarree`
809831
- :grid: :class:`bool` - default True
810832
- :grid_labels: :class:`bool` - default True
833+
- :grid_fontsize: :class:`float` - default 10.0
811834
- :basemap: :class:`str`. Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link. Default is None
812835
- :coastline: :class:`bool` - Flag to plot coastline. default True,
813836
- :borders: :class:`bool` - Flag to plot country borders. default False,
837+
- :region_border: :class:`bool` - Flag to plot the dataset region border. default True,
838+
- :tile_scaling: :class:`str`/:class:`int`. Zoom level (1-12) of the basemap tiles. If 'auto', is automatically derived from extent
814839
- :linewidth: :class:`float` - Line width of borders and coast lines. default 1.5,
815840
- :linecolor: :class:`str` - Color of borders and coast lines. default 'black',
816841
- :cmap: :class:`str`/:class:`pyplot.colors.Colormap` - default 'viridis'
817-
- :clabel: :class:`str` - default None
818-
- :clim: :class:`list` - default None
842+
- :clim: :class:`list` - Range of the colorbar. default None
843+
- :clabel: :class:`str` - Label of the colorbar. default None
844+
- :clabel_fontsize: :class:`float` - default None
845+
- :cticks_fontsize: :class:`float` - default None
819846
- :alpha: :class:`float` - default 1
820847
- :alpha_exp: :class:`float` - Exponent for the alpha func (recommended between 0.4 and 1). default 0
821848
@@ -841,16 +868,20 @@ def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_
841868
projection = plot_args.get('projection', ccrs.PlateCarree(central_longitude=0.0))
842869
grid = plot_args.get('grid', True)
843870
grid_labels = plot_args.get('grid_labels', False)
871+
grid_fontsize = plot_args.get('grid_fontsize', False)
844872
basemap = plot_args.get('basemap', None)
845873
coastline = plot_args.get('coastline', True)
846874
borders = plot_args.get('borders', False)
875+
tile_scaling = plot_args.get('tile_scaling', 'auto')
847876
linewidth = plot_args.get('linewidth', True)
848877
linecolor = plot_args.get('linecolor', 'black')
849878
region_border = plot_args.get('region_border', True)
850879
# color bar properties
851880
cmap = plot_args.get('cmap', None)
852-
clabel = plot_args.get('clabel', '')
853881
clim = plot_args.get('clim', None)
882+
clabel = plot_args.get('clabel', None)
883+
clabel_fontsize = plot_args.get('clabel_fontsize', None)
884+
cticks_fontsize = plot_args.get('cticks_fontsize', None)
854885
alpha = plot_args.get('alpha', 1)
855886
alpha_exp = plot_args.get('alpha_exp', 0)
856887

@@ -862,7 +893,7 @@ def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_
862893
n_lats = len(region.ys) // 2
863894
central_latitude = region.ys[n_lats]
864895

865-
# Instantiage GeoAxes object
896+
# Instantiate GeoAxes object
866897
if ax is None:
867898
fig = pyplot.figure(figsize=figsize)
868899
ax = fig.add_subplot(111, projection=projection)
@@ -877,7 +908,7 @@ def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_
877908
# Basemap plotting
878909
ax = plot_basemap(basemap, extent, ax=ax, coastline=coastline, borders=borders,
879910
linecolor=linecolor, linewidth=linewidth, projection=projection, apprx=apprx,
880-
central_latitude=central_latitude)
911+
central_latitude=central_latitude, tile_scaling=tile_scaling)
881912

882913
## Define colormap and transparency function
883914
if isinstance(cmap, str) or not cmap:
@@ -902,22 +933,25 @@ def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_
902933
cax = fig.add_axes([ax.get_position().x1 + 0.01, ax.get_position().y0, 0.025, ax.get_position().height],
903934
label='Colorbar')
904935
cbar = fig.colorbar(im, ax=ax, cax=cax)
905-
cbar.set_label(clabel)
936+
cbar.set_label(clabel, fontsize=clabel_fontsize)
937+
cbar.ax.tick_params(labelsize=cticks_fontsize)
906938

907939
# Gridline options
908940
if grid:
909941
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
910942
gl.right_labels = False
911943
gl.top_labels = False
944+
gl.xlabel_style['fontsize'] = grid_fontsize
945+
gl.ylabel_style['fontsize'] = grid_fontsize
912946
gl.xformatter = LONGITUDE_FORMATTER
913947
gl.yformatter = LATITUDE_FORMATTER
914948

915949
if region_border:
916950
pts = region.tight_bbox()
917-
ax.plot(pts[:,0], pts[:,1], lw=1, color='black', transform=ccrs.PlateCarree())
951+
ax.plot(pts[:, 0], pts[:, 1], lw=1, color='black', transform=ccrs.PlateCarree())
918952

919953
# matplotlib figure options
920-
ax.set_title(title, y=1.06)
954+
ax.set_title(title, y=1.06, fontsize=title_size)
921955
if filename is not None:
922956
ax.get_figure().savefig(filename + '.pdf')
923957
ax.get_figure().savefig(filename + '.png', dpi=300)

0 commit comments

Comments
 (0)