Skip to content

Commit

Permalink
make repo black compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
cvanelteren committed Jan 11, 2025
1 parent 7aa82a2 commit 5483796
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 50 deletions.
39 changes: 15 additions & 24 deletions ultraplot/axes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1982,7 +1982,9 @@ def _parse_colorbar_inset(
)
ticklocation = _not_none(tickloc=tickloc, ticklocation=ticklocation)
if ticklocation is not None and ticklocation != "bottom":
warnings._warn_ultraplot("Inset colorbars can only have ticks on the bottom.")
warnings._warn_ultraplot(
"Inset colorbars can only have ticks on the bottom."
)
kwargs.update({"orientation": "horizontal", "ticklocation": "bottom"})
return ax, kwargs

Expand Down Expand Up @@ -2619,21 +2621,18 @@ def _update_super_labels(self, side, labels=None, **kwargs):
if labels or kw:
fig._update_super_labels(side, labels, **kw)


@staticmethod
def get_center_of_axes(axes = None):
def get_center_of_axes(axes=None):
positions = [ax.get_position() for ax in axes]
# get the outermost coordinates
box = mtransforms.Bbox.from_extents(
min(p.bounds[0] for p in positions),
min(p.bounds[1] for p in positions),
max(p.bounds[0] + p.bounds[2] for p in positions),
max(p.bounds[1] + p.bounds[3] for p in positions)
max(p.bounds[1] + p.bounds[3] for p in positions),
)
return box



def _update_share_labels(self, axes=None, target="x"):
"""Update shared axis labels for a group of axes.
Expand All @@ -2654,33 +2653,26 @@ def _update_share_labels(self, axes=None, target="x"):
# Get the center position of the axes group
if box := self.get_center_of_axes(axes):
# Reuse existing label if possible
if target == 'x':
if target == "x":
label = axes[0].xaxis.label
# Update position and properties
label.set_position((
(box.bounds[0] + box.bounds[2])/2,
box.bounds[1]
))
label.set_position(((box.bounds[0] + box.bounds[2]) / 2, box.bounds[1]))
else: # y-axis
label = axes[0].yaxis.label
# Update position and properties
label.set_position((
box.bounds[0],
(box.bounds[1] + box.bounds[3])/2
))
label.set_position((box.bounds[0], (box.bounds[1] + box.bounds[3]) / 2))

label.set_ha('center')
label.set_va('center')
label.set_ha("center")
label.set_va("center")

# Share the same label object across all axes
# Skip first axes since we used its label
for ax in axes[1:]:
if target == 'x':
if target == "x":
ax.xaxis.label = label
else:
ax.yaxis.label = label


@docstring._snippet_manager
def format(
self,
Expand All @@ -2706,8 +2698,8 @@ def format(
lowercentertitle=None,
lrtitle=None,
lowerrighttitle=None,
share_xlabels = None,
share_ylabels = None,
share_xlabels=None,
share_ylabels=None,
**kwargs,
):
"""
Expand Down Expand Up @@ -2751,12 +2743,11 @@ def format(
if above is not None:
self._title_above = above # used for future titles


# Update a-b-c label and titles
abc_kw = abc_kw or {}
title_kw = title_kw or {}
self._update_share_labels(share_xlabels, target = 'x')
self._update_share_labels(share_ylabels, target = 'y')
self._update_share_labels(share_xlabels, target="x")
self._update_share_labels(share_ylabels, target="y")
self._update_abc(**abc_kw)
self._update_title(None, title, **title_kw)
self._update_title(
Expand Down
43 changes: 31 additions & 12 deletions ultraplot/axes/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1822,7 +1822,9 @@ def _fix_patch_edges(obj, edgefix=None, **kwargs):
for element in obj:
PlotAxes._fix_patch_edges(element, edgefix=edgefix)
else:
warnings._warn_ultraplot(f"Unexpected obj {obj} passed to _fix_patch_edges.")
warnings._warn_ultraplot(
f"Unexpected obj {obj} passed to _fix_patch_edges."
)

@contextlib.contextmanager
def _keep_grid_bools(self):
Expand Down Expand Up @@ -3471,7 +3473,15 @@ def _apply_scatter(self, xs, ys, ss, cc, *, vert=True, **kwargs):
and test.shape[1] in (3, 4)
):
infer_rgb = False
cc, kw = self._parse_color(xs, ys, cc, inbounds=inbounds, apply_cycle=False, infer_rgb=infer_rgb, **kw)
cc, kw = self._parse_color(
xs,
ys,
cc,
inbounds=inbounds,
apply_cycle=False,
infer_rgb=infer_rgb,
**kw,
)

guide_kw = _pop_params(kw, self._update_guide)
objs = []
Expand Down Expand Up @@ -4401,21 +4411,28 @@ def streamplot(self, x, y, u, v, c, **kwargs):
self._update_guide(m.lines, queue_colorbar=False, **guide_kw) # use lines
return m


@inputs._parse_triangulation_with_preprocess('x', 'y', 'z', keywords=['triangles'])
@inputs._parse_triangulation_with_preprocess("x", "y", "z", keywords=["triangles"])
@docstring._concatenate_inherited
@docstring._snippet_manager
def tricontour(self, *args, **kwargs):
"""
%(plot.tricontour)s
"""
kw = kwargs.copy()
triangulation, z, args, kwargs = inputs._parse_triangulation_inputs(*args, **kwargs)
triangulation, z, args, kwargs = inputs._parse_triangulation_inputs(
*args, **kwargs
)

# Update kwargs and handle cmap
kw.update(_pop_props(kw, "collection"))
kw = self._parse_cmap(
triangulation.x, triangulation.y, z, min_levels=1, plot_lines=True, plot_contours=True, **kw
triangulation.x,
triangulation.y,
z,
min_levels=1,
plot_lines=True,
plot_contours=True,
**kw,
)

# Handle labels and guide parameters
Expand All @@ -4433,8 +4450,7 @@ def tricontour(self, *args, **kwargs):

return m


@inputs._parse_triangulation_with_preprocess('x', 'y', 'z', keywords=['triangles'])
@inputs._parse_triangulation_with_preprocess("x", "y", "z", keywords=["triangles"])
@docstring._concatenate_inherited
@docstring._snippet_manager
def tricontourf(self, *args, **kwargs):
Expand All @@ -4447,7 +4463,9 @@ def tricontourf(self, *args, **kwargs):
# Update kwargs and handle contour parameters
kw.update(_pop_props(kw, "collection"))
contour_kw = _pop_kwargs(kw, "edgecolors", "linewidths", "linestyles")
kw = self._parse_cmap(triangulation.x, triangulation.y, z, plot_contours=True, **kw)
kw = self._parse_cmap(
triangulation.x, triangulation.y, z, plot_contours=True, **kw
)

# Handle patch edges, labels, and guide parameters
edgefix_kw = _pop_params(kw, self._fix_patch_edges)
Expand All @@ -4463,16 +4481,17 @@ def tricontourf(self, *args, **kwargs):
# Fix edges and add labels
self._fix_patch_edges(m, **edgefix_kw, **contour_kw) # No-op if not contour_kw
if contour_kw or labels_kw:
cm = self._fix_contour_edges("tricontour", triangulation.x, triangulation.y, z, **kw, **contour_kw)
cm = self._fix_contour_edges(
"tricontour", triangulation.x, triangulation.y, z, **kw, **contour_kw
)

# Add auto labels and update the guide
self._add_auto_labels(m, cm, **labels_kw)
self._update_guide(m, queue_colorbar=False, **guide_kw)

return m


@inputs._parse_triangulation_with_preprocess('x', 'y', 'z', keywords=['triangles'])
@inputs._parse_triangulation_with_preprocess("x", "y", "z", keywords=["triangles"])
@docstring._concatenate_inherited
@docstring._snippet_manager
def tripcolor(self, *args, **kwargs):
Expand Down
12 changes: 9 additions & 3 deletions ultraplot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,9 @@ def _validate_key(key, value=None):
key = key.lower()
if "." not in key:
key = rcsetup._rc_nodots.get(key, key)
key, value = rc_ultraplot._check_key(key, value) # may issue deprecation warning
key, value = rc_ultraplot._check_key(
key, value
) # may issue deprecation warning
return key, value

@staticmethod
Expand Down Expand Up @@ -1621,7 +1623,9 @@ def _load_file(self, path):
value = self._validate_value(key, value)
except KeyError:
warnings.simplefilter("default", warnings.UltraplotWarning)
warnings._warn_ultraplot(f"Invalid rc key {key!r} on {message}.")
warnings._warn_ultraplot(
f"Invalid rc key {key!r} on {message}."
)
continue
except ValueError as err:
warnings.simplefilter("default", warnings.UltraplotWarning)
Expand Down Expand Up @@ -1679,7 +1683,9 @@ def _save_yaml(path, user_dict=None, *, comment=False, description=False):
user_table = rcsetup._yaml_table(user_dict, comment=False)
user_table = ("# Changed settings", user_table, "")
ultraplot_dict = (
rcsetup._rc_ultraplot_table if description else rcsetup._rc_ultraplot_default
rcsetup._rc_ultraplot_table
if description
else rcsetup._rc_ultraplot_default
) # noqa: E501
ultraplot_table = rcsetup._yaml_table(
ultraplot_dict, comment=comment, description=description
Expand Down
4 changes: 3 additions & 1 deletion ultraplot/demos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1114,7 +1114,9 @@ def show_fonts(
if opts and opts[0] in all_names:
props.append(arg)
else:
warnings._warn_ultraplot(f"Input font name {opts[:1]!r} not found. Skipping.")
warnings._warn_ultraplot(
f"Input font name {opts[:1]!r} not found. Skipping."
)

# Add user and family FontProperties.
user = _not_none(user, not args and family is None)
Expand Down
8 changes: 6 additions & 2 deletions ultraplot/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,9 @@ def __init__(
f"Ignoring subplotpars={pars!r}. " + self._space_message
)
if kwargs.pop("tight_layout", None):
warnings._warn_ultraplot("Ignoring tight_layout=True. " + self._tight_message)
warnings._warn_ultraplot(
"Ignoring tight_layout=True. " + self._tight_message
)
if kwargs.pop("constrained_layout", None):
warnings._warn_ultraplot(
"Ignoring constrained_layout=True. " + self._tight_message
Expand Down Expand Up @@ -2092,7 +2094,9 @@ def _get_deprecated(self, attr=_attr):

@functools.wraps(_func) # noqa: E301
def _disable_method(self, *args, func=_func, message=_msg, **kwargs):
message = f"fig.{func.__name__}() has no effect on ultraplot figures. " + message
message = (
f"fig.{func.__name__}() has no effect on ultraplot figures. " + message
)
if self._is_authorized:
return func(self, *args, **kwargs)
else:
Expand Down
18 changes: 14 additions & 4 deletions ultraplot/internals/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,34 +254,44 @@ def _from_data(data, *args):
return args



def _parse_triangulation_inputs(*args, **kwargs):
"""
Parse inputs using Matplotlib's `get_from_args_and_kwargs` method.
Returns a Triangulation object, z values, and updated args/kwargs.
"""
from matplotlib.tri import Triangulation
triangulation, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)

triangulation, args, kwargs = Triangulation.get_from_args_and_kwargs(
*args, **kwargs
)
if not args:
raise ValueError("No z values provided. Provide at least one positional argument for z.")
raise ValueError(
"No z values provided. Provide at least one positional argument for z."
)
z = args[0] # Assume the first remaining argument is z
return triangulation, z, args[1:], kwargs


def _parse_triangulation_with_preprocess(*keys, keywords=None, allow_extra=True):
"""
Combines _parse_triangulation with _preprocess_or_redirect for backwards compatibility.
"""

def _decorator(func):
@_preprocess_or_redirect(*keys, keywords=keywords, allow_extra=allow_extra)
def wrapper(self, *args, **kwargs):
# Parse triangulation inputs after preprocessing
triangulation, z, remaining_args, updated_kwargs = _parse_triangulation_inputs(*args, **kwargs)
triangulation, z, remaining_args, updated_kwargs = (
_parse_triangulation_inputs(*args, **kwargs)
)
# Call the original function with parsed inputs
return func(self, triangulation, z, *remaining_args, **updated_kwargs)

return wrapper

return _decorator


def _preprocess_or_redirect(*keys, keywords=None, allow_extra=True):
"""
Redirect internal plotting calls to native matplotlib methods. Also convert
Expand Down
11 changes: 9 additions & 2 deletions ultraplot/internals/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -1909,7 +1909,9 @@ def copy(self):
# and the original matplotlib RcParams. Also surreptitiously add ultraplot
# font settings to the font keys list (beoolean below always evalutes to True)
# font keys list whlie initializing.
_rc_ultraplot_default = {key: value for key, (value, _, _) in _rc_ultraplot_table.items()}
_rc_ultraplot_default = {
key: value for key, (value, _, _) in _rc_ultraplot_table.items()
}
_rc_ultraplot_validate = {
key: validator
for key, (_, validator, _) in _rc_ultraplot_table.items()
Expand All @@ -1928,6 +1930,11 @@ def copy(self):
}
_rc_nodots = {
name.replace(".", ""): name
for dict_ in (_rc_ultraplot_default, _rc_matplotlib_native, _rc_renamed, _rc_removed)
for dict_ in (
_rc_ultraplot_default,
_rc_matplotlib_native,
_rc_renamed,
_rc_removed,
)
for name in dict_.keys()
}
5 changes: 3 additions & 2 deletions ultraplot/tests/test_1dplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,10 +372,12 @@ def test_scatter_sizes():
ax.text(i, 0.5, format(d, ".0f"), va="center", ha="center")
return fig


# Test introduced by issue #https://github.com/Ultraplot/ultraplot/issues/12#issuecomment-2576154882
# Check for concave triangulation related functions
from matplotlib import tri


@pytest.mark.mpl_image_compare
@pytest.mark.mpl_image_compare
@pytest.mark.parametrize(
Expand All @@ -397,7 +399,6 @@ def test_scatter_sizes():
(*base_data[:3], None, False, False),
# Test using data dictionary
(*base_data[:3], None, False, True),
],
)
def test_triplot_variants(x, y, z, triangles, use_triangulation, use_datadict):
Expand All @@ -410,7 +411,7 @@ def test_triplot_variants(x, y, z, triangles, use_triangulation, use_datadict):
triangulation = tri.Triangulation(x, y, triangles)
ax.tricontourf(triangulation, z, levels=64, cmap="PuBu")
elif use_datadict:
ax.tricontourf("x", "y", "z", data = df)
ax.tricontourf("x", "y", "z", data=df)
return
else:
# Use direct x, y, z inputs
Expand Down

0 comments on commit 5483796

Please sign in to comment.