Skip to content

Commit

Permalink
Add font size traits to various classes (Fixes #1805)
Browse files Browse the repository at this point in the history
Add titlesize trait to MapPanel. Add clabelsize trait to ContourTraits. Add colorbar_fontsize trait to ColorfillTraits. Add font_size trait to PlotObs.
  • Loading branch information
23ccozad committed Jun 4, 2021
1 parent d91a89e commit c8a5137
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 6 deletions.
43 changes: 37 additions & 6 deletions src/metpy/plots/declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,15 @@ class MapPanel(Panel):
This trait sets a user-defined title that will plot at the top center of the figure.
"""

titlesize = Union([Int(), Float(), Unicode()], allow_none=True, default_value=None)
titlesize.__doc__ = """An integer or string value for the font size of the title of the
figure.
This trait sets the font size for the title that will plot at the top center of the figure.
Accepts size in points or relative size. Allowed relative sizes are those of Matplotlib:
'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'.
"""

@observe('plots')
def _plots_changed(self, change):
"""Handle when our collection of plots changes."""
Expand Down Expand Up @@ -756,7 +765,7 @@ def draw(self):

# Use the set title or generate one.
title = self.title or ',\n'.join(plot.name for plot in self.plots)
self.ax.set_title(title)
self.ax.set_title(title, fontsize=self.titlesize)
self._need_redraw = False

def __copy__(self):
Expand Down Expand Up @@ -987,8 +996,9 @@ def draw(self):
if getattr(self, 'handle', None) is None:
self._build()
if getattr(self, 'colorbar', None) is not None:
self.parent.ax.figure.colorbar(
self.handle, orientation=self.colorbar, pad=0, aspect=50)
self.parent.ax.figure.colorbar(self.handle, orientation=self.colorbar,
pad=0, aspect=50)\
.ax.tick_params(labelsize=self.colorbar_fontsize)
self._need_redraw = False


Expand All @@ -1010,6 +1020,14 @@ class ContourTraits(HasTraits):
To plot contour labels set this trait to ``True``, the default value is ``False``.
"""

clabelsize = Union([Int(), Float(), Unicode()], allow_none=True, default_value=None)
clabelsize.__doc__ = """An integer, float, or string value to set the font size of labels for contours.
This trait sets the font size for labels that will plot along contour lines. Accepts
size in points or relative size. Allowed relative sizes are those of Matplotlib:
'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'.
"""


class ColorfillTraits(HasTraits):
"""Represent common colorfill traits."""
Expand Down Expand Up @@ -1037,6 +1055,15 @@ class ColorfillTraits(HasTraits):
``None``.
"""

colorbar_fontsize = Union([Int(), Float(), Unicode()], allow_none=True, default_value=None)
colorbar_fontsize.__doc__ = """An integer, float, or string value to set the font size of
labels for the colorbar.
This trait sets the font size of labels for the colorbar. Accepts size in points or
relative size. Allowed relative sizes are those of Matplotlib: 'xx-small', 'x-small',
'small', 'medium', 'large', 'x-large', 'xx-large'.
"""


@exporter.export
class ImagePlot(PlotScalar, ColorfillTraits):
Expand Down Expand Up @@ -1115,7 +1142,7 @@ class ContourPlot(PlotScalar, ContourTraits):
dashdot.
"""

@observe('contours', 'linecolor', 'linewidth', 'linestyle', 'clabels')
@observe('contours', 'linecolor', 'linewidth', 'linestyle', 'clabels', 'clabelsize')
def _set_need_rebuild(self, _):
"""Handle changes to attributes that need to regenerate everything."""
# Because matplotlib doesn't let you just change these properties, we need
Expand All @@ -1131,7 +1158,7 @@ def _build(self):
transform=imdata.metpy.cartopy_crs)
if self.clabels:
self.handle.clabel(inline=1, fmt='%.0f', inline_spacing=8,
use_clabeltext=True)
use_clabeltext=True, fontsize=self.clabelsize)


@exporter.export
Expand Down Expand Up @@ -1431,6 +1458,10 @@ class PlotObs(HasTraits):
plotting using the MetPy Units module, provided that units are attached to the DataFrame.
"""

font_size = Int(10)
font_size.__doc__ = """An integer value to set the font size of station plots. Default
is 10 pt."""

def clear(self):
"""Clear the plot.
Expand Down Expand Up @@ -1579,7 +1610,7 @@ def _build(self):
subset = reduce_point_density(point_locs, self.reduce_points * scale)

self.handle = StationPlot(self.parent.ax, lon[subset], lat[subset], clip_on=True,
transform=ccrs.PlateCarree(), fontsize=10)
transform=ccrs.PlateCarree(), fontsize=self.font_size)

for i, ob_type in enumerate(self.fields):
field_kwargs = {}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
60 changes: 60 additions & 0 deletions tests/plots/test_declarative.py
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,66 @@ def test_declarative_multiple_sfc_obs_change_units(ccrs):
return pc.figure


@pytest.mark.mpl_image_compare(remove_text=True, tolerance=0.607)
@needs_cartopy
def test_declarative_font_sizes():
"""Test all font size attributes."""
data = xr.open_dataset(get_test_data('GFS_test.nc', as_file_obj=False))

cntr = ContourPlot()
cntr.data = data
cntr.field = 'Geopotential_height_isobaric'
cntr.level = 300 * units.hPa
cntr.time = datetime(2010, 10, 26, 12)
cntr.contours = list(range(0, 10000, 120))
cntr.linecolor = 'black'
cntr.linestyle = 'solid'
cntr.clabels = True
cntr.clabelsize = 18

cfill = FilledContourPlot()
cfill.data = data
cfill.field = 'Temperature_isobaric'
cfill.level = 300 * units.hPa
cfill.time = datetime(2010, 10, 26, 12)
cfill.contours = list(range(210, 250, 2))
cfill.colormap = 'BuPu'
cfill.colorbar = 'horizontal'
cfill.colorbar_fontsize = 'x-small'

data2 = parse_metar_file(get_test_data('metar_20190701_1200.txt',
as_file_obj=False), year=2019, month=7)
obs = PlotObs()
obs.data = data2
obs.time = datetime(2019, 7, 1, 12)
obs.time_window = timedelta(minutes=15)
obs.level = None
obs.fields = ['cloud_coverage', 'air_temperature', 'dew_point_temperature',
'air_pressure_at_sea_level', 'current_wx1_symbol']
obs.plot_units = [None, 'degF', 'degF', None, None]
obs.locations = ['C', 'NW', 'SW', 'NE', 'W']
obs.formats = ['sky_cover', None, None, lambda v: format(v * 10, '.0f')[-3:],
'current_weather']
obs.reduce_points = 3
obs.vector_field = ['eastward_wind', 'northward_wind']
obs.font_size = 7

panel = MapPanel()
panel.area = 'centus'
panel.projection = 'data'
panel.layers = ['coastline', 'borders', 'usstates']
panel.plots = [cntr, cfill, obs]
panel.title = '300 hPa Height and Temperature; Surface Obs'
panel.titlesize = 'xx-large'

pc = PanelContainer()
pc.size = (8, 8)
pc.panels = [panel]
pc.draw()

return pc.figure


def test_save():
"""Test that our saving function works."""
pc = PanelContainer()
Expand Down

0 comments on commit c8a5137

Please sign in to comment.