How to use the proplot.utils.units function in proplot

To help you get started, we’ve selected a few proplot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lukelbd / proplot / proplot / axes.py View on Github external
}
            override = getattr(self, 'grid_override', None)
            grid = _default(grid, override)
            gridminor = _default(gridminor, override)
            for which,igrid in zip(('major', 'minor'), (grid,gridminor)):
                # Tick properties
                kw_ticks = rc.category(xyname + 'tick.' + which)
                if kw_ticks is None:
                    kw_ticks = {}
                else:
                    kw_ticks.pop('visible', None) # invalid setting
                if ticklen is not None:
                    if which=='major':
                        kw_ticks['size'] = utils.units(ticklen, 'pt')
                    else:
                        kw_ticks['size'] = utils.units(ticklen, 'pt') * rc.get('ticklenratio')
                # Grid style and toggling
                if igrid is not None:
                    axis.grid(igrid, which=which) # toggle with special global props
                if which=='major':
                    kw_grid = rc.fill(grid_dict('grid'))
                else:
                    kw_major = kw_grid
                    kw_grid = rc.fill(grid_dict('gridminor'))
                    kw_grid.update({key:value for key,value in kw_major.items() if key not in kw_grid})
                # Changed rc settings
                axis.set_tick_params(which=which, **kw_grid, **kw_ticks)

            # Tick and ticklabel properties that apply to both major and minor
            # * Weird issue seems to cause set_tick_params to reset/forget that the grid
            #   is turned on if you access tick.gridOn directly, instead of passing through tick_params.
            #   Since gridOn is undocumented feature, don't use it. So calling _format_axes() a second time will remove the lines
github lukelbd / proplot / proplot / figure.py View on Github external
'1 (hide axis labels), '
                '2 (share limits and hide axis labels), or '
                '3 (share limits and hide axis and tick labels).'
            )
        self._alignx = bool(alignx)
        self._aligny = bool(aligny)
        self._sharex = int(sharex)
        self._sharey = int(sharey)
        self._spanx = bool(spanx)
        self._spany = bool(spany)

        # Various other attributes
        gridspec_kw = gridspec_kw or {}
        gridspec = pgridspec.GridSpec(self, **gridspec_kw)
        nrows, ncols = gridspec.get_active_geometry()
        self._pad = units(_not_none(pad, rc['subplots.pad']))
        self._axpad = units(_not_none(axpad, rc['subplots.axpad']))
        self._panelpad = units(_not_none(panelpad, rc['subplots.panelpad']))
        self._auto_tight = _not_none(tight, rc['subplots.tight'])
        self._include_panels = includepanels
        self._fallback_to_cm = fallback_to_cm
        self._ref_num = ref
        self._axes_main = []
        self._subplots_orig_kw = subplots_orig_kw
        self._subplots_kw = subplots_kw
        self._bottom_panels = []
        self._top_panels = []
        self._left_panels = []
        self._right_panels = []
        self._bottom_array = np.empty((0, ncols), dtype=bool)
        self._top_array = np.empty((0, ncols), dtype=bool)
        self._left_array = np.empty((0, nrows), dtype=bool)
github lukelbd / proplot / proplot / figure.py View on Github external
"""
    Return default properties for new axes and figure panels.
    """
    if side not in ('left', 'right', 'bottom', 'top'):
        raise ValueError(f'Invalid panel location {side!r}.')

    space = space_user = units(space)
    if share is None:
        share = not filled

    if width is None:
        if filled:
            width = rc['colorbar.width']
        else:
            width = rc['subplots.panelwidth']
    width = units(width)

    if space is None:
        key = 'wspace' if side in ('left', 'right') else 'hspace'
        pad = rc['subplots.axpad'] if figure else rc['subplots.panelpad']
        space = pgridspec._default_space(key, share, pad=pad)

    return share, width, space, space_user
github lukelbd / proplot / proplot / subplots.py View on Github external
for name,value in zip(names,values):
        if value is not None:
            warnings.warn(f'You specified both {spec} and {name}={repr(value)}. Ignoring "{name}".')
    # Standardize input
    width  = units(width)
    height = units(height)
    axwidth  = units(axwidth)
    axheight = units(axheight)
    # Gridspec defaults
    # NOTE: Ratios are scaled to take physical units in _subplots_kwargs, so
    # user can manually provide hspace and wspace in physical units.
    hspace = np.atleast_1d(units(_default(hspace,
        rc['subplot.titlespace'] + rc['subplot.innerspace'] if sharex==3
        else rc['subplot.xlabspace'] if sharex in (1,2) # space for tick labels and title
        else rc['subplot.titlespace'] + rc['subplot.xlabspace'])))
    wspace = np.atleast_1d(units(_default(wspace,
        rc['subplot.innerspace'] if sharey==3
        else rc['subplot.ylabspace'] - rc['subplot.titlespace'] if sharey in (1,2) # space for tick labels only
        else rc['subplot.ylabspace']
        )))
    wratios = np.atleast_1d(_default(width_ratios, wratios, axwidths, 1))
    hratios = np.atleast_1d(_default(height_ratios, hratios, axheights, 1))
    if len(wspace)==1:
        wspace = np.repeat(wspace, (ncols-1,))
    if len(hspace)==1:
        hspace = np.repeat(hspace, (nrows-1,))
    if flush or wflush:
        wspace = wspace*0.0
    if flush or hflush:
        hspace = hspace*0.0
    if len(wratios)==1:
        wratios = np.repeat(wratios, (ncols,))
github lukelbd / proplot / proplot / subplots.py View on Github external
auto_height = (height is None and width is not None)
    auto_neither = (width is not None and height is not None)
    bpanel_space = sum(bwidth) + sum(bsep) + bspace if bspan else 0
    rpanel_space = sum(rwidth) + sum(rsep) + rspace if rspan else 0
    lpanel_space = sum(lwidth) + sum(lsep) + lspace if lspan else 0
    if np.iterable(aspect):
        aspect = aspect[0]/aspect[1]
    # Determine figure dims from axes width and height
    # Default behavior: axes average 2.0 inches wide
    # aspect = aspect*(hratios[0]/np.mean(hratios))
    # NOTE: Account for 'whitespace' that is spanned by our reference axes.
    # When user passes 'axwidth' or 'axheight' they mean the width or height
    # of the entire thing including the part spanning over empty space.
    if auto_both: # get stuff directly from axes
        if axwidth is None and axheight is None:
            axwidth = units(rc['subplot.axwidth'])
        if axheight is not None:
            auto_width = True
            axheight_all = ((axheight - rhspace)/dy/rhratio)*nrows # must omit space covered by reference axes
            height = axheight_all + top + bottom + sum(hspace) + sum(hpanels) + bpanel_space
        if axwidth is not None:
            auto_height = True
            axwidth_all = ((axwidth - rwspace)/dx/rwratio)*ncols
            width = axwidth_all + left + right + sum(wspace) + sum(wpanels) + rpanel_space + lpanel_space
        if axwidth is not None and axheight is not None:
            auto_width = auto_height = False
    # Determine axes widths and heights from requested figure dims
    # Make sure to exclude the 'wpanels' and 'hpanels' props
    else:
        if auto_width or auto_neither:
            axheight_all = height - top - bottom - sum(hspace) - sum(hpanels) - bpanel_space
            axheight = (axheight_all*dy/nrows) + rhspace # reverse engineered from above
github lukelbd / proplot / proplot / subplots.py View on Github external
# Widths
        width = _panel_prop(side, 'width', ('panelwidth', 'cbarwidth', 'legwidth'))
        width = np.atleast_1d(units(width))
        if len(width)==1:
            width = np.repeat(width, (stack,))
        if len(width)!=stack:
            raise ValueError(f'For side "{side}", have {stack} stacked panels, but got {len(width)} widths.')
        kwout[side + 'width'] = width
        # Panel separation
        flush = _panel_prop(side, 'flush', False)
        if stack==1 or flush:
            sep = 0
        else:
            default = 'nolabspace' if share else 'ylabspace' if side in 'lr' else 'xlabspace'
            sep = _panel_prop(side, 'sep', (default,default,default))
        sep = np.atleast_1d(units(sep))
        if len(sep)==1:
            sep = np.repeat(sep, (stack-1,))
        if len(sep)!=stack-1:
            raise ValueError(f'For side "{side}", have {stack} stacked panels, but got {len(sep)} separations.')
        kwout[side + 'sep'] = sep
        kwout[side + 'flush'] = flush

    # Properties for figure panels or axes panels
    if figure:
        for side in allpanels:
            # Space between panels and main subplots
            space = _panel_prop(side, 'space', 'xlabspace' if side=='b' else 'ylabspace' if side=='l' else 'nolabspace')
            kwout[side + 'space'] = units(space)
            # Spanning of panels along subplot rows and columns
            nmax = ncols if side=='b' else nrows
            span = _panel_prop(side, 'span', False)
github lukelbd / proplot / proplot / subplots.py View on Github external
spec = []
        if width is not None:
            spec.append(f'width={repr(width)}')
        if height is not None:
            spec.append(f'height="{repr(height)}"')
        spec = ', '.join(spec)
        names = ('axwidth', 'axheight')
        values = (axwidth, axheight)
    # Raise warning
    for name,value in zip(names,values):
        if value is not None:
            warnings.warn(f'You specified both {spec} and {name}={repr(value)}. Ignoring "{name}".')
    # Standardize input
    width  = units(width)
    height = units(height)
    axwidth  = units(axwidth)
    axheight = units(axheight)
    # Gridspec defaults
    # NOTE: Ratios are scaled to take physical units in _subplots_kwargs, so
    # user can manually provide hspace and wspace in physical units.
    hspace = np.atleast_1d(units(_default(hspace,
        rc['subplot.titlespace'] + rc['subplot.innerspace'] if sharex==3
        else rc['subplot.xlabspace'] if sharex in (1,2) # space for tick labels and title
        else rc['subplot.titlespace'] + rc['subplot.xlabspace'])))
    wspace = np.atleast_1d(units(_default(wspace,
        rc['subplot.innerspace'] if sharey==3
        else rc['subplot.ylabspace'] - rc['subplot.titlespace'] if sharey in (1,2) # space for tick labels only
        else rc['subplot.ylabspace']
        )))
    wratios = np.atleast_1d(_default(width_ratios, wratios, axwidths, 1))
    hratios = np.atleast_1d(_default(height_ratios, hratios, axheights, 1))
    if len(wspace)==1:
github lukelbd / proplot / proplot / config.py View on Github external
if key is None:  # means setting was removed
            return {}, {}, {}
        keys = (key,) + rcsetup._rc_children.get(key, ())  # settings to change
        value = self._sanitize_value(value)
        kw_proplot = {}  # custom properties that global setting applies to
        kw_matplotlib = {}  # builtin properties that global setting applies to

        # Permit arbitary units for builtin matplotlib params
        # See: https://matplotlib.org/users/customizing.html, props matching
        # the below strings use the units 'points'.
        # TODO: Incorporate into more sophisticated validation system
        if any(REGEX_POINTS.match(_) for _ in keys):
            try:
                self._scale_font(value)  # *validate* but do not translate
            except KeyError:
                value = units(value, 'pt')

        # Special key: configure inline backend
        if key == 'inlinefmt':
            config_inline_backend(value)

        # Special key: apply stylesheet
        elif key == 'style':
            if value is not None:
                kw_matplotlib, kw_proplot = _get_style_dicts(value, infer=True)

        # Cycler
        elif key == 'cycle':
            colors = _get_cycle_colors(value)
            kw_matplotlib['patch.facecolor'] = 'C0'
            kw_matplotlib['axes.prop_cycle'] = cycler.cycler('color', colors)
github lukelbd / proplot / proplot / ui.py View on Github external
names = ('axwidth', 'axheight')
        values = (axwidth, axheight)
    # Raise warning
    for name, value in zip(names, values):
        if value is not None:
            warnings._warn_proplot(
                f'You specified both {spec} and {name}={value!r}. '
                f'Ignoring {name!r}.'
            )

    # Standardized dimensions
    width, height = units(width), units(height)
    axwidth, axheight = units(axwidth), units(axheight)

    # Standardized user input border spaces
    left, right = units(left), units(right)
    bottom, top = units(bottom), units(top)

    # Standardized user input spaces
    wspace = np.atleast_1d(units(_not_none(wspace, space)))
    hspace = np.atleast_1d(units(_not_none(hspace, space)))
    if len(wspace) == 1:
        wspace = np.repeat(wspace, (ncols - 1,))
    if len(wspace) != ncols - 1:
        raise ValueError(
            f'Require {ncols-1} width spacings for {ncols} columns, '
            'got {len(wspace)}.'
        )
    if len(hspace) == 1:
        hspace = np.repeat(hspace, (nrows - 1,))
    if len(hspace) != nrows - 1:
        raise ValueError(