Skip to content

Small style fixes. #22721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/devel/MEP/MEP26.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Detailed description
====================

Currently, the look and appearance of existing artist objects (figure,
axes, Line2D etc...) can only be updated via ``set_`` and ``get_`` methods
axes, Line2D, etc.) can only be updated via ``set_`` and ``get_`` methods
on the artist object, which is quite laborious, especially if no
reference to the artist(s) has been stored. The new style sheets
introduced in 1.4 allow styling before a plot is created, but do not
Expand All @@ -51,7 +51,7 @@ of primitives.
The new methodology would require development of a number of steps:

- A new stylesheet syntax (likely based on CSS) to allow selection of
artists by type, class, id etc...
artists by type, class, id, etc.
- A mechanism by which to parse a stylesheet into a tree
- A mechanism by which to translate the parse-tree into something
which can be used to update the properties of relevant
Expand Down
2 changes: 1 addition & 1 deletion doc/devel/documenting_mpl.rst
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ Keyword arguments

Since Matplotlib uses a lot of pass-through ``kwargs``, e.g., in every function
that creates a line (`~.pyplot.plot`, `~.pyplot.semilogx`, `~.pyplot.semilogy`,
etc...), it can be difficult for the new user to know which ``kwargs`` are
etc.), it can be difficult for the new user to know which ``kwargs`` are
supported. Matplotlib uses a docstring interpolation scheme to support
documentation of every function that takes a ``**kwargs``. The requirements
are:
Expand Down
4 changes: 2 additions & 2 deletions examples/event_handling/pick_event_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
===============

You can enable picking by setting the "picker" property of an artist
(for example, a matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc...)
(for example, a Matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc.)

There are a variety of meanings of the picker property:

Expand Down
10 changes: 2 additions & 8 deletions examples/misc/custom_projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,14 +270,8 @@ def format_coord(self, lon, lat):
In this case, we want them to be displayed in degrees N/S/E/W.
"""
lon, lat = np.rad2deg([lon, lat])
if lat >= 0.0:
ns = 'N'
else:
ns = 'S'
if lon >= 0.0:
ew = 'E'
else:
ew = 'W'
ns = 'N' if lat >= 0.0 else 'S'
ew = 'E' if lon >= 0.0 else 'W'
return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
% (abs(lat), ns, abs(lon), ew))

Expand Down
13 changes: 7 additions & 6 deletions examples/text_labels_and_annotations/usetex_fonteffects.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ def setfont(font):


fig = plt.figure()
for y, font, text in zip(range(5),
['ptmr8r', 'ptmri8r', 'ptmro8r',
'ptmr8rn', 'ptmrr8re'],
['Nimbus Roman No9 L ' + x for x in
['', 'Italics (real italics for comparison)',
'(slanted)', '(condensed)', '(extended)']]):
for y, font, text in zip(
range(5),
['ptmr8r', 'ptmri8r', 'ptmro8r', 'ptmr8rn', 'ptmrr8re'],
[f'Nimbus Roman No9 L {x}'
for x in ['', 'Italics (real italics for comparison)',
'(slanted)', '(condensed)', '(extended)']],
):
fig.text(.1, 1 - (y + 1) / 6, setfont(font) + text, usetex=True)

fig.suptitle('Usetex font effects')
Expand Down
20 changes: 10 additions & 10 deletions examples/user_interfaces/toolmanager_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@
Tool Manager
============

This example demonstrates how to:
This example demonstrates how to

* Modify the Toolbar
* Create tools
* Add tools
* Remove tools
* modify the Toolbar
* create tools
* add tools
* remove tools

Using `matplotlib.backend_managers.ToolManager`
using `matplotlib.backend_managers.ToolManager`.
"""

import matplotlib.pyplot as plt
plt.rcParams['toolbar'] = 'toolmanager'
from matplotlib.backend_tools import ToolBase, ToolToggleBase


plt.rcParams['toolbar'] = 'toolmanager'


class ListTools(ToolBase):
"""List all the tools controlled by the `ToolManager`."""
# keyboard shortcut
default_keymap = 'm'
default_keymap = 'm' # keyboard shortcut
description = 'List Tools'

def trigger(self, *args, **kwargs):
Expand Down Expand Up @@ -77,7 +78,6 @@ def set_lines_visibility(self, state):
fig.canvas.manager.toolmanager.add_tool('List', ListTools)
fig.canvas.manager.toolmanager.add_tool('Show', GroupHideTool, gid='mygroup')


# Add an existing tool to new group `foo`.
# It can be added as many times as we want
fig.canvas.manager.toolbar.add_tool('zoom', 'foo')
Expand Down
2 changes: 1 addition & 1 deletion examples/userdemo/anchored_box04.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

fig, ax = plt.subplots(figsize=(3, 3))

box1 = TextArea(" Test : ", textprops=dict(color="k"))
box1 = TextArea(" Test: ", textprops=dict(color="k"))

box2 = DrawingArea(60, 20, 0, 0)
el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r")
Expand Down
34 changes: 13 additions & 21 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2878,26 +2878,23 @@ def handle_single_axis(
shared = shared_axes.get_siblings(self)
# Base autoscaling on finite data limits when there is at least one
# finite data limit among all the shared_axes and intervals.
# Also, find the minimum minpos for use in the margin calculation.
x_values = []
minimum_minpos = np.inf
for ax in shared:
x_values.extend(getattr(ax.dataLim, f"interval{name}"))
minimum_minpos = min(minimum_minpos,
getattr(ax.dataLim, f"minpos{name}"))
x_values = np.extract(np.isfinite(x_values), x_values)
if x_values.size >= 1:
x0, x1 = (x_values.min(), x_values.max())
values = [val for ax in shared
for val in getattr(ax.dataLim, f"interval{name}")
if np.isfinite(val)]
if values:
x0, x1 = (min(values), max(values))
elif getattr(self._viewLim, f"mutated{name}")():
# No data, but explicit viewLims already set:
# in mutatedx or mutatedy.
return
else:
x0, x1 = (-np.inf, np.inf)
# If x0 and x1 are non finite, use the locator to figure out
# default limits.
# If x0 and x1 are nonfinite, get default limits from the locator.
locator = axis.get_major_locator()
x0, x1 = locator.nonsingular(x0, x1)
# Find the minimum minpos for use in the margin calculation.
minimum_minpos = min(
getattr(ax.dataLim, f"minpos{name}") for ax in shared)

# Prevent margin addition from crossing a sticky value. A small
# tolerance must be added due to floating point issues with
Expand Down Expand Up @@ -4027,15 +4024,10 @@ def format_ydata(self, y):

def format_coord(self, x, y):
"""Return a format string formatting the *x*, *y* coordinates."""
if x is None:
xs = '???'
else:
xs = self.format_xdata(x)
if y is None:
ys = '???'
else:
ys = self.format_ydata(y)
return 'x=%s y=%s' % (xs, ys)
return "x={} y={}".format(
"???" if x is None else self.format_xdata(x),
"???" if y is None else self.format_ydata(y),
)

def minorticks_on(self):
"""
Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/backends/backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,10 +459,7 @@ def _make_id(self, type, content):
return '%s%s' % (type, m.hexdigest()[:10])

def _make_flip_transform(self, transform):
return (transform +
Affine2D()
.scale(1.0, -1.0)
.translate(0.0, self.height))
return transform + Affine2D().scale(1, -1).translate(0, self.height)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The multi-line version is arguably more readable but not going to block over that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+/-0


def _get_font(self, prop):
fname = fm.findfont(prop)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def points_to_pixels(self, points):

class GraphicsContextTemplate(GraphicsContextBase):
"""
The graphics context provides the color, line styles, etc... See the cairo
The graphics context provides the color, line styles, etc. See the cairo
and postscript backends for examples of mapping the graphics context
attributes (cap styles, join styles, line widths, colors) to a particular
backend. In cairo this is done by wrapping a cairo.Context object and
Expand All @@ -131,7 +131,7 @@ class GraphicsContextTemplate(GraphicsContextBase):
########################################################################
#
# The following functions and classes are for pyplot and implement
# window/figure managers, etc...
# window/figure managers, etc.
#
########################################################################

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_wx.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def points_to_pixels(self, points):

class GraphicsContextWx(GraphicsContextBase):
"""
The graphics context provides the color, line styles, etc...
The graphics context provides the color, line styles, etc.

This class stores a reference to a wxMemoryDC, and a
wxGraphicsContext that draws to it. Creating a wxGraphicsContext
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1129,9 +1129,9 @@ def legend_elements(self, prop="colors", num="auto",
ix = np.argsort(xarr)
values = np.interp(label_values, xarr[ix], yarr[ix])

kw = dict(markeredgewidth=self.get_linewidths()[0],
alpha=self.get_alpha())
kw.update(kwargs)
kw = {"markeredgewidth": self.get_linewidths()[0],
"alpha": self.get_alpha(),
**kwargs}

for val, lab in zip(values, label_values):
if prop == "colors":
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ def json_load(filename):
--------
json_dump
"""
with open(filename, 'r') as fh:
with open(filename) as fh:
return json.load(fh, object_hook=_json_decode)


Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,7 @@ def val_or_rc(val, rc_name):
colors.to_rgba_array(labelcolor))):
text.set_color(color)
else:
raise ValueError("Invalid argument for labelcolor : %s" %
str(labelcolor))
raise ValueError(f"Invalid labelcolor: {labelcolor!r}")

def _set_artist_props(self, a):
"""
Expand Down Expand Up @@ -943,8 +942,7 @@ def set_bbox_to_anchor(self, bbox, transform=None):
try:
l = len(bbox)
except TypeError as err:
raise ValueError("Invalid argument for bbox : %s" %
str(bbox)) from err
raise ValueError(f"Invalid bbox: {bbox}") from err

if l == 2:
bbox = [bbox[0], bbox[1], 0, 0]
Expand Down
16 changes: 9 additions & 7 deletions lib/matplotlib/mpl-data/matplotlibrc
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@
## ***************************************************************************
#image.aspect: equal # {equal, auto} or a number
#image.interpolation: antialiased # see help(imshow) for options
#image.cmap: viridis # A colormap name, gray etc...
#image.cmap: viridis # A colormap name (plasma, magma, etc.)
#image.lut: 256 # the size of the colormap lookup table
#image.origin: upper # {lower, upper}
#image.resample: True
Expand Down Expand Up @@ -679,12 +679,14 @@
# 'tight' is incompatible with pipe-based animation
# backends (e.g. 'ffmpeg') but will work with those
# based on temporary files (e.g. 'ffmpeg_file')
#savefig.pad_inches: 0.1 # Padding to be used when bbox is set to 'tight'
#savefig.directory: ~ # default directory in savefig dialog box,
# leave empty to always use current working directory
#savefig.transparent: False # setting that controls whether figures are saved with a
# transparent background by default
#savefig.orientation: portrait # Orientation of saved figure
#savefig.pad_inches: 0.1 # padding to be used, when bbox is set to 'tight'
#savefig.directory: ~ # default directory in savefig dialog, gets updated after
# interactive saves, unless set to the empty string (i.e.
# the current directory); use '.' to start at the current
# directory but update after interactive saves
#savefig.transparent: False # whether figures are saved with a transparent
# background by default
#savefig.orientation: portrait # orientation of saved figure, for PostScript output only

### tk backend params
#tk.window_focus: False # Maintain shell focus for TkAgg
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/mpl-data/stylelib/classic.mplstyle
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ figure.subplot.hspace : 0.2 # the amount of height reserved for space betwee
### IMAGES
image.aspect : equal # equal | auto | a number
image.interpolation : bilinear # see help(imshow) for options
image.cmap : jet # gray | jet etc...
image.cmap : jet # gray | jet | ...
image.lut : 256 # the size of the colormap lookup table
image.origin : upper # lower | upper
image.resample : False
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1064,8 +1064,7 @@ def set_bbox_to_anchor(self, bbox, transform=None):
try:
l = len(bbox)
except TypeError as err:
raise ValueError("Invalid argument for bbox : %s" %
str(bbox)) from err
raise ValueError(f"Invalid bbox: {bbox}") from err

if l == 2:
bbox = [bbox[0], bbox[1], 0, 0]
Expand Down
13 changes: 4 additions & 9 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -2181,28 +2181,23 @@ class _Style:
where actual styles are declared as subclass of it, and it
provides some helper functions.
"""

def __new__(cls, stylename, **kwargs):
"""Return the instance of the subclass with the given style name."""

# The "class" should have the _style_list attribute, which is a mapping
# of style names to style classes.

_list = stylename.replace(" ", "").split(",")
_name = _list[0].lower()
try:
_cls = cls._style_list[_name]
except KeyError as err:
raise ValueError("Unknown style : %s" % stylename) from err

raise ValueError(f"Unknown style: {stylename}") from err
try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = {k: float(v) for k, v in _args_pair}
except ValueError as err:
raise ValueError("Incorrect style argument : %s" %
stylename) from err
_args.update(kwargs)

return _cls(**_args)
raise ValueError(f"Incorrect style argument: {stylename}") from err
return _cls(**{**_args, **kwargs})

@classmethod
def get_styles(cls):
Expand Down
10 changes: 2 additions & 8 deletions lib/matplotlib/projections/geo.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,8 @@ def set_xlim(self, *args, **kwargs):
def format_coord(self, lon, lat):
"""Return a format string formatting the coordinate."""
lon, lat = np.rad2deg([lon, lat])
if lat >= 0.0:
ns = 'N'
else:
ns = 'S'
if lon >= 0.0:
ew = 'E'
else:
ew = 'W'
ns = 'N' if lat >= 0.0 else 'S'
ew = 'E' if lon >= 0.0 else 'W'
return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
% (abs(lat), ns, abs(lon), ew))

Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -1443,7 +1443,7 @@ def _get_xy_transform(self, renderer, s):
elif isinstance(tr, Transform):
return tr
else:
raise RuntimeError("unknown return type ...")
raise RuntimeError("Unknown return type")
elif isinstance(s, Artist):
bbox = s.get_window_extent(renderer)
return BboxTransformTo(bbox)
Expand All @@ -1452,7 +1452,7 @@ def _get_xy_transform(self, renderer, s):
elif isinstance(s, Transform):
return s
elif not isinstance(s, str):
raise RuntimeError("unknown coordinate type : %s" % s)
raise RuntimeError(f"Unknown coordinate type: {s!r}")

if s == 'data':
return self.axes.transData
Expand Down
Loading