Skip to content
Merged
14 changes: 12 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ ProPlot v0.7.0 (2021-06-30)
Make the ``Browns1`` map the most colorful/vibrant one, just
like ``Greens1`` and ``Blues1``; split up the ``RedPurple`` maps into ``Reds`` and
``Purples``; and add the ``Yellows`` category from the ``Oranges`` maps (:commit:`8be0473f`).
* Rename seldom-used `Figure` argument `fallback_to_cm` to more understandable
`mathtext_fallback` (:pr:`251`).

.. rubric:: Features

Expand Down Expand Up @@ -121,6 +123,16 @@ ProPlot v0.7.0 (2021-06-30)

.. rubric:: Bug fixes

* Fix 3 fatal issues preventing proplot import and basic usage in matplotlib >= 3.4
(:pr:`251`).
* Fix deprecation warnings associated with matplotlib 3.4 refactoring of
subplot classes (:pr:`251`).
* Fix deprecated reference to :rc:`fallback_to_cm` in matplotlib >= 3.3
(:pr:`251`).
* Fix `~matplotlib.ticker.IndexFormatter` deprecation warning in matplotlib >= 3.3 by
replacing with proplot-local copy (:pr:`251`).
* Fix deprecation warning in matplotlib >= 3.3 -- add `extend` as mappable attribute
rather than passing it to `colorbar()` (:commit:`a23e7043`).
* Fix issue where axis is accidentally inverted for histogram plots (:issue:`191`).
* Fix issue where numeric zero cannot be applied as legend label (:commit:`02417c8c`).
* Fix issue where `~proplot.colors.Cycle` fails to register new names and fails to
Expand Down Expand Up @@ -150,8 +162,6 @@ ProPlot v0.7.0 (2021-06-30)
nested ragged arrays from parametric coords (:commit:`b16d56a8`).
* Fix issue where where `SubplotSpec.get_active_rows_columns` returned incorrect
number of "active" rows and columns (:commit:`5cf20b84`).
* Fix deprecation warning in matplotlib >= 3.3 -- add `extend` as mappable attribute
rather than passing it to `colorbar()` (:commit:`a23e7043`).
* For rc lookup with `context=True`, use most restrictive search mode rather than least.
Otherwise `ax.format()` calls inside context blocks can be overwritten with the
default rc values in subsequent `ax.format()` calls (:commit:`8005fcc1`).
Expand Down
19 changes: 15 additions & 4 deletions proplot/axes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ class Axes(maxes.Axes):
Lowest-level axes subclass. Handles titles and axis
sharing. Adds several new methods and overrides existing ones.
"""
def __init__(self, *args, number=None, main=False, **kwargs):
def __init__(self, *args, number=None, main=False, _subplotspec=None, **kwargs):
"""
Parameters
----------
Expand Down Expand Up @@ -259,7 +259,7 @@ def __init__(self, *args, number=None, main=False, **kwargs):

# Figure row and column labels
# NOTE: Most of these sit empty for most subplots
# TODO: Implement this with EdgeStack
# TODO: Implement this with EdgeStack, avoid creating silly empty objects
coltransform = mtransforms.blended_transform_factory(
self.transAxes, self.figure.transFigure
)
Expand Down Expand Up @@ -303,9 +303,20 @@ def __init__(self, *args, number=None, main=False, **kwargs):
# Abc label
self._abc_label = self.text(0, 0, '', transform=transform)

# Automatic axis sharing and formatting
# TODO: Instead of format() call specific setters
# Subplot spec
# WARNING: For mpl>=3.4.0 subplotspec assigned *after* initialization using
# set_subplotspec. Tried to defer to setter but really messes up both format()
# and _auto_share_setup(). Instead use workaround: Have Figure.add_subplot pass
# subplotspec as a hidden keyword arg. Non-subplots don't need this arg.
# See https://github.com/matplotlib/matplotlib/pull/18564
if _subplotspec is not None:
self.set_subplotspec(_subplotspec)

# Automatic axis sharing
self._auto_share_setup()

# Automatic formatting
# TODO: Apply specific setters instead of format()
self.format(rc_mode=1) # mode == 1 applies the custom proplot params

def _auto_share_setup(self):
Expand Down
21 changes: 17 additions & 4 deletions proplot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import cycler
import matplotlib as mpl
import matplotlib.cbook as cbook
import matplotlib.colors as mcolors
import matplotlib.font_manager as mfonts
import matplotlib.mathtext # noqa
Expand All @@ -30,6 +29,11 @@
from .internals import _not_none, docstring, rcsetup, timers, warnings
from .utils import to_xyz, units

try:
from matplotlib.cbook import _suppress_matplotlib_deprecation_warning # mpl<3.4.0
except ImportError:
from matplotlib._api import suppress_matplotlib_deprecation_warning as _suppress_matplotlib_deprecation_warning # noqa: E501

try:
from IPython import get_ipython
except ImportError:
Expand Down Expand Up @@ -1094,7 +1098,7 @@ def _get_default_dict():
# WARNING: Some deprecated rc params remain in dictionary as None so we
# filter them out. Beware if hidden attribute changes.
rcdict = _get_filtered_dict(mpl.rcParamsDefault, warn=False)
with cbook._suppress_matplotlib_deprecation_warning():
with _suppress_matplotlib_deprecation_warning():
rcdict = dict(RcParams(rcdict))
for attr in ('_deprecated_remain_as_none', '_deprecated_set'):
if hasattr(mpl, attr): # _deprecated_set is in matplotlib before v3
Expand Down Expand Up @@ -1456,10 +1460,19 @@ def register_fonts():
if not fnames_all >= fnames_proplot:
warnings._warn_proplot('Rebuilding font cache.')
if hasattr(mfonts.fontManager, 'addfont'):
# New API lets us add font files manually
# New API lets us add font files manually and deprecates TTFPATH. However,
# to cache fonts added this way, we must call json_dump explicitly.
# NOTE: Previously, cache filename was specified as _fmcache variable, but
# recently became inaccessible. Must reproduce mpl code instead! Annoying.
# NOTE: Older mpl versions used fontList.json as the cache, but these
# versions also did not have 'addfont', so makes no difference.
for fname in fnames_proplot:
mfonts.fontManager.addfont(fname)
mfonts.json_dump(mfonts.fontManager, mfonts._fmcache)
cache = os.path.join(
mpl.get_cachedir(),
f'fontlist-v{mfonts.FontManager.__version__}.json'
)
mfonts.json_dump(mfonts.fontManager, cache)
else:
# Old API requires us to modify TTFPATH
# NOTE: Previously we tried to modify TTFPATH before importing
Expand Down
6 changes: 3 additions & 3 deletions proplot/constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
'logit': mticker.LogitFormatter,
'eng': mticker.EngFormatter,
'percent': mticker.PercentFormatter,
'index': mticker.IndexFormatter,
'index': pticker._IndexFormatter,
'e': partial(pticker.FracFormatter, symbol=r'$e$', number=np.e),
'pi': partial(pticker.FracFormatter, symbol=r'$\pi$', number=np.pi),
'tau': partial(pticker.FracFormatter, symbol=r'$\tau$', number=2 * np.pi),
Expand Down Expand Up @@ -1080,7 +1080,7 @@ def Formatter(formatter, *args, date=False, index=False, **kwargs):
elif np.iterable(formatter):
# List of strings
if index:
formatter = mticker.IndexFormatter(formatter)
formatter = pticker._IndexFormatter(formatter)
else:
formatter = mticker.FixedFormatter(formatter)
else:
Expand Down Expand Up @@ -1363,7 +1363,7 @@ def Proj(name, basemap=None, **kwargs):
raise RuntimeError(
'Basemap is no longer maintained and is incompatible with '
'matplotlib >= 3.3. Please use cartopy as your cartographic '
'plotting backend or downgrade to matplotlib <=3.2.'
'plotting backend or downgrade to matplotlib <= 3.2.'
)
if 'lonlim' in kwargs:
kwargs['llcrnrlon'], kwargs['urcrnrlon'] = kwargs.pop('lonlim')
Expand Down
2 changes: 1 addition & 1 deletion proplot/demos.py
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,7 @@ def show_fonts(
fig, axs = ui.subplots(
ncols=1, nrows=len(args), space=0,
axwidth=4.5, axheight=1.2 * (text.count('\n') + 2.5) * size / 72,
fallback_to_cm=False
mathtext_fallback=False
)
axs.format(
xloc='neither', yloc='neither',
Expand Down
53 changes: 37 additions & 16 deletions proplot/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,22 @@
import os

import matplotlib.figure as mfigure
import matplotlib.gridspec as mgridspec
import matplotlib.transforms as mtransforms
import numpy as np

from . import axes as paxes
from . import gridspec as pgridspec
from .config import rc
from .internals import ic # noqa: F401
from .internals import _dummy_context, _not_none, _state_context, warnings
from .internals import (
_dummy_context,
_not_none,
_state_context,
_version,
_version_mpl,
warnings,
)
from .utils import units

__all__ = ['Figure']
Expand Down Expand Up @@ -88,8 +96,14 @@ def _preprocess(self, *args, **kwargs):
# and displaying within inline notebook backend (previously worked around
# this by forcing additional draw() call in this function before proceeding
# with print_figure). Solution is to use _state_context with _cachedRenderer.
fallback = _not_none(fig._fallback_to_cm, rc['mathtext.fallback_to_cm'])
rc_context = rc.context({'mathtext.fallback_to_cm': fallback})
local = fig._mathtext_fallback
if local is None:
context = {}
elif _version_mpl >= _version('3.4'):
context = {'mathtext.fallback': local if isinstance(local, str) else 'cm' if local else None} # noqa: E501
else:
context = {'mathtext.fallback_to_cm': bool(local)}
rc_context = rc.context(context)
fig_context = fig._context_preprocessing(cache=(method != 'print_figure'))
with rc_context, fig_context:
fig.auto_layout()
Expand Down Expand Up @@ -136,7 +150,7 @@ def __init__(
align=None, alignx=None, aligny=None,
share=None, sharex=None, sharey=None,
gridspec_kw=None, subplots_kw=None, subplots_orig_kw=None,
fallback_to_cm=None,
mathtext_fallback=None,
**kwargs
):
"""
Expand Down Expand Up @@ -194,9 +208,11 @@ def __init__(
<https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/align_labels_demo.html>`__
for the *x* axis, *y* axis, or both axes. Only has an effect when `spanx`,
`spany`, or `span` are ``False``. Default is :rc:`subplots.align`.
fallback_to_cm : bool, optional
Whether to replace unavailable glyphs with a glyph from Computer Modern
or the "¤" dummy character. See `mathtext \
mathtext_fallback : bool or str, optional
Figure-specific application of the :rc:`mathtext.fallback` property.
If ``True`` or string, unavailable glyphs are replaced with a glyph from a
fallback font (Computer Modern by default). Otherwise, they are replaced
with the "¤" dummy character. See `mathtext \
<https://matplotlib.org/3.1.1/tutorials/text/mathtext.html#custom-fonts>`__
for details.
gridspec_kw, subplots_kw, subplots_orig_kw
Expand Down Expand Up @@ -268,7 +284,7 @@ def __init__(
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._mathtext_fallback = mathtext_fallback
self._ref_num = ref
self._axes_main = []
self._subplots_orig_kw = subplots_orig_kw
Expand Down Expand Up @@ -699,9 +715,7 @@ def _get_align_axes(self, side):
edge = min_ if side in ('left', 'top') else max_

# Return axes on edge sorted by order of appearance
axs = [
ax for ax in self._axes_main if ax._range_gridspec(x)[idx] == edge
]
axs = [ax for ax in self._axes_main if ax._range_gridspec(x)[idx] == edge]
ranges = [ax._range_gridspec(y)[0] for ax in axs]
return [ax for _, ax in sorted(zip(ranges, axs)) if ax.get_visible()]

Expand Down Expand Up @@ -812,11 +826,12 @@ def _insert_row_column(
elif subplotspec_top is gridspec_ss._subplot_spec:
gridspec_ss._subplot_spec = subplotspec_new
else:
raise ValueError(
'Unexpected GridSpecFromSubplotSpec nesting.'
)
ax.update_params()
ax.set_position(ax.figbox)
raise ValueError('Unexpected GridSpecFromSubplotSpec nesting.')
if _version_mpl >= _version('3.4'):
ax.set_position(ax.get_subplotspec().get_position(ax.figure))
else:
ax.update_params()
ax.set_position(ax.figbox) # equivalent to above

# Adjust figure size *after* gridspecs are fixed
self.set_size_inches(figsize, auto=True)
Expand Down Expand Up @@ -1046,6 +1061,12 @@ def add_subplot(self, *args, **kwargs):
'Using "fig.add_subplot()" with ProPlot figures may result in '
'unexpected behavior. Please use "proplot.subplots()" instead.'
)
if (
len(args) == 1
and isinstance(args[0], mgridspec.SubplotSpec)
and kwargs.get('projection', None) in ('cartesian', 'polar2', 'basemap', 'cartopy') # noqa: E501
):
kwargs['_subplotspec'] = args[0] # mpl>=3.4.0 workaround: see Axes.__init__
return super().add_subplot(*args, **kwargs)

def auto_layout(self, renderer=None, resize=None, aspect=None, tight=None):
Expand Down
9 changes: 6 additions & 3 deletions proplot/gridspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from .config import rc
from .internals import ic # noqa: F401
from .internals import _not_none
from .internals import _not_none, _version, _version_mpl
from .utils import units

__all__ = ['GridSpec', 'SubplotSpec']
Expand Down Expand Up @@ -583,8 +583,11 @@ def update(self, **kwargs):
subplotspec = ax.get_subplotspec().get_topmost_subplotspec()
if subplotspec.get_gridspec() is not self:
continue
ax.update_params()
ax.set_position(ax.figbox)
if _version_mpl >= _version('3.4.0'):
ax.set_position(ax.get_subplotspec().get_position(ax.figure))
else:
ax.update_params()
ax.set_position(ax.figbox) # equivalent to above
fig.stale = True


Expand Down
4 changes: 2 additions & 2 deletions proplot/internals/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@
}

# ProPlot overrides of matplotlib default style
# NOTE: Hard to say what best value for 'margin' is. 0 is bad for bar plots and scatter
# plots, 0.05 is good for line plot in y direction but not x direction.
# WARNING: Critical to include every parameter here that can be changed by a
# "meta" setting so that _get_default_param returns the value imposed by *proplot*
# and so that "changed" settings detectd by RcConfigurator.save are correct.
# NOTE: Hard to say what best value for 'margin' is. 0 is bad for bar plots and scatter
# plots, 0.05 is good for line plot in y direction but not x direction.
_rc_matplotlib_default = {
'axes.axisbelow': GRIDBELOW,
'axes.formatter.use_mathtext': MATHTEXT,
Expand Down
19 changes: 19 additions & 0 deletions proplot/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,25 @@ def _hemisphere(self, value, *args, **kwargs): # noqa: U100
return ''


class _IndexFormatter(mticker.Formatter):
"""
Duplication of the exceedingly simple `~matplotlib.ticker.IndexFormatter`
class deprecated in matplotlib 3.3.0.
"""
# NOTE: For details check out https://github.com/matplotlib/matplotlib/issues/16631
# and bring some popcorn.
def __init__(self, labels):
self.labels = labels
self.n = len(labels)

def __call__(self, x, pos=None): # noqa: U100
i = int(round(x))
if i < 0 or i >= self.n:
return ''
else:
return self.labels[i]


class AutoFormatter(mticker.ScalarFormatter):
"""
The new default formatter. Differs from `~matplotlib.ticker.ScalarFormatter`
Expand Down