Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit dfb3556

Browse filesBrowse files
committed
Allow empty linestyle for collections
1 parent a861b8a commit dfb3556
Copy full SHA for dfb3556

17 files changed

+261
-140
lines changed

‎ci/mypy-stubtest-allowlist.txt

Copy file name to clipboardExpand all lines: ci/mypy-stubtest-allowlist.txt
-1Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ matplotlib.ticker.LogLocator.set_params
8181
matplotlib.axes._base._AxesBase.axis
8282

8383
# Aliases (dynamically generated, not type hinted)
84-
matplotlib.collections.Collection.get_dashes
8584
matplotlib.collections.Collection.get_ec
8685
matplotlib.collections.Collection.get_edgecolors
8786
matplotlib.collections.Collection.get_facecolors

‎lib/matplotlib/axes/_axes.py

Copy file name to clipboardExpand all lines: lib/matplotlib/axes/_axes.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8055,7 +8055,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None,
80558055
if 'linestyle' in kwargs:
80568056
raise _api.kwarg_error("spy", "linestyle")
80578057
ret = mlines.Line2D(
8058-
x, y, linestyle='None', marker=marker, markersize=markersize,
8058+
x, y, linestyle='none', marker=marker, markersize=markersize,
80598059
**kwargs)
80608060
self.add_line(ret)
80618061
nr, nc = Z.shape

‎lib/matplotlib/collections.py

Copy file name to clipboardExpand all lines: lib/matplotlib/collections.py
+87-64Lines changed: 87 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"antialiased": ["antialiaseds", "aa"],
2929
"edgecolor": ["edgecolors", "ec"],
3030
"facecolor": ["facecolors", "fc"],
31-
"linestyle": ["linestyles", "dashes", "ls"],
31+
"linestyle": ["linestyles", "ls"],
3232
"linewidth": ["linewidths", "lw"],
3333
"offset_transform": ["transOffset"],
3434
})
@@ -79,7 +79,7 @@ def __init__(self, *,
7979
edgecolors=None,
8080
facecolors=None,
8181
linewidths=None,
82-
linestyles='solid',
82+
linestyles='-',
8383
capstyle=None,
8484
joinstyle=None,
8585
antialiaseds=None,
@@ -104,15 +104,8 @@ def __init__(self, *,
104104
Face color for each patch making up the collection.
105105
linewidths : float or list of floats, default: :rc:`patch.linewidth`
106106
Line width for each patch making up the collection.
107-
linestyles : str or tuple or list thereof, default: 'solid'
108-
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
109-
'--', '-.', ':']. Dash tuples should be of the form::
110-
111-
(offset, onoffseq),
112-
113-
where *onoffseq* is an even length tuple of on and off ink lengths
114-
in points. For examples, see
115-
:doc:`/gallery/lines_bars_and_markers/linestyles`.
107+
linestyles : str or tuple or list thereof, default: '-'
108+
Line style or list of line styles. See `set_linestyle` for details.
116109
capstyle : `.CapStyle`-like, default: :rc:`patch.capstyle`
117110
Style to use for capping lines for all paths in the collection.
118111
Allowed values are %(CapStyle)s.
@@ -156,11 +149,12 @@ def __init__(self, *,
156149
cm.ScalarMappable.__init__(self, norm, cmap)
157150
# list of un-scaled dash patterns
158151
# this is needed scaling the dash pattern by linewidth
159-
self._us_linestyles = [(0, None)]
152+
self._unscaled_dash_patterns = [(0, None)]
160153
# list of dash patterns
161-
self._linestyles = [(0, None)]
154+
self._dash_patterns = [(0, None)]
155+
self._linestyles = ['-']
162156
# list of unbroadcast/scaled linewidths
163-
self._us_lw = [0]
157+
self._unscaled_lw = [0]
164158
self._linewidths = [0]
165159

166160
self._gapcolor = None # Currently only used by LineCollection.
@@ -379,7 +373,7 @@ def draw(self, renderer):
379373
if (len(paths) == 1 and len(trans) <= 1 and
380374
len(facecolors) == 1 and len(edgecolors) == 1 and
381375
len(self._linewidths) == 1 and
382-
all(ls[1] is None for ls in self._linestyles) and
376+
all(dash[1] is None for dash in self._dash_patterns) and
383377
len(self._antialiaseds) == 1 and len(self._urls) == 1 and
384378
self.get_hatch() is None):
385379
if len(trans):
@@ -400,7 +394,7 @@ def draw(self, renderer):
400394
if do_single_path_optimization:
401395
gc.set_foreground(tuple(edgecolors[0]))
402396
gc.set_linewidth(self._linewidths[0])
403-
gc.set_dashes(*self._linestyles[0])
397+
gc.set_dashes(*self._dash_patterns[0])
404398
gc.set_antialiased(self._antialiaseds[0])
405399
gc.set_url(self._urls[0])
406400
renderer.draw_markers(
@@ -422,7 +416,7 @@ def draw(self, renderer):
422416
gc, transform.frozen(), paths,
423417
self.get_transforms(), offsets, offset_trf,
424418
self.get_facecolor(), self.get_edgecolor(),
425-
self._linewidths, self._linestyles,
419+
self._linewidths, self._dash_patterns,
426420
self._antialiaseds, self._urls,
427421
"screen") # offset_position, kept for backcompat.
428422

@@ -579,54 +573,82 @@ def set_linewidth(self, lw):
579573
if lw is None:
580574
lw = self._get_default_linewidth()
581575
# get the un-scaled/broadcast lw
582-
self._us_lw = np.atleast_1d(lw)
576+
self._unscaled_lw = np.atleast_1d(lw)
583577

584578
# scale all of the dash patterns.
585-
self._linewidths, self._linestyles = self._bcast_lwls(
586-
self._us_lw, self._us_linestyles)
579+
self._linewidths, self._dash_patterns = self._bcast_lwls(
580+
self._unscaled_lw, self._unscaled_dash_patterns)
587581
self.stale = True
588582

589583
def set_linestyle(self, ls):
590584
"""
591-
Set the linestyle(s) for the collection.
585+
Set the line style(s) for the collection.
586+
587+
Parameters
588+
----------
589+
ls : str or tuple or list thereof
590+
The line style. Possible values:
592591
593-
=========================== =================
594-
linestyle description
595-
=========================== =================
596-
``'-'`` or ``'solid'`` solid line
597-
``'--'`` or ``'dashed'`` dashed line
598-
``'-.'`` or ``'dashdot'`` dash-dotted line
599-
``':'`` or ``'dotted'`` dotted line
600-
=========================== =================
592+
- A string:
601593
602-
Alternatively a dash tuple of the following form can be provided::
594+
========================================== =================
595+
linestyle description
596+
========================================== =================
597+
``'-'`` or ``'solid'`` solid line
598+
``'--'`` or ``'dashed'`` dashed line
599+
``'-.'`` or ``'dashdot'`` dash-dotted line
600+
``':'`` or ``'dotted'`` dotted line
601+
``'none'``, ``'None'``, ``' '``, or ``''`` draw nothing
602+
========================================== =================
603603
604-
(offset, onoffseq),
604+
- Alternatively a dash tuple of the following form can be
605+
provided::
605606
606-
where ``onoffseq`` is an even length tuple of on and off ink in points.
607+
(offset, onoffseq)
607608
608-
Parameters
609-
----------
610-
ls : str or tuple or list thereof
611-
Valid values for individual linestyles include {'-', '--', '-.',
612-
':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a
613-
complete description.
609+
where ``onoffseq`` is an even length tuple of on and off ink
610+
in points.
611+
612+
If a single value is provided, this applies to all objects in the
613+
collection. A list can be provided to set different line styles to
614+
different objects.
615+
616+
For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
617+
618+
The ``'dashed'``, ``'dashdot'``, and ``'dotted'`` line styles are
619+
controlled by :rc:`lines.dashed_pattern`,
620+
:rc:`lines.dashdot_pattern`, and :rc:`lines.dotted_pattern`,
621+
respectively.
614622
"""
615-
try:
616-
dashes = [mlines._get_dash_pattern(ls)]
617-
except ValueError:
623+
if isinstance(ls, str):
624+
dashes, ls_norm = map(list, zip(mlines._get_dash_pattern(ls)))
625+
elif not ls:
626+
dashes, ls_norm = [], []
627+
else:
618628
try:
619-
dashes = [mlines._get_dash_pattern(x) for x in ls]
620-
except ValueError as err:
621-
emsg = f'Do not know how to convert {ls!r} to dashes'
622-
raise ValueError(emsg) from err
629+
dashes, ls_norm = map(list, zip(mlines._get_dash_pattern(ls)))
630+
except ValueError:
631+
dashes, ls_norm = map(
632+
list, zip(*[mlines._get_dash_pattern(x) for x in ls]))
623633

624634
# get the list of raw 'unscaled' dash patterns
625-
self._us_linestyles = dashes
635+
self._unscaled_dash_patterns = dashes
626636

627637
# broadcast and scale the lw and dash patterns
628-
self._linewidths, self._linestyles = self._bcast_lwls(
629-
self._us_lw, self._us_linestyles)
638+
self._linewidths, self._dash_patterns = self._bcast_lwls(
639+
self._unscaled_lw, self._unscaled_dash_patterns)
640+
self._linestyles = ls_norm
641+
642+
# Dashes used to be an alias of linestyle
643+
set_dashes = set_linestyle
644+
645+
def get_dashes(self):
646+
"""
647+
Return the dash patterns.
648+
649+
.. versionadded:: 3.8
650+
"""
651+
return self._dash_patterns
630652

631653
@_docstring.interpd
632654
def set_capstyle(self, cs):
@@ -827,7 +849,12 @@ def get_linewidth(self):
827849
return self._linewidths
828850

829851
def get_linestyle(self):
830-
return self._linestyles
852+
_api.warn_external(
853+
"Collection.get_linestyle will change return type from a list of dash "
854+
"pattern to a list of linestyle strings. This is consistent with Line2D. "
855+
"To get the previous result now and in the future without this warning, "
856+
"use get_dashes.")
857+
return self.get_dashes()
831858

832859
def _set_mappable_flags(self):
833860
"""
@@ -918,8 +945,10 @@ def update_from(self, other):
918945
self._original_facecolor = other._original_facecolor
919946
self._facecolors = other._facecolors
920947
self._linewidths = other._linewidths
948+
self._unscaled_lw = other._unscaled_lw
921949
self._linestyles = other._linestyles
922-
self._us_linestyles = other._us_linestyles
950+
self._unscaled_dash_patterns = other._unscaled_dash_patterns
951+
self._dash_patterns = other._dash_patterns
923952
self._pickradius = other._pickradius
924953
self._hatch = other._hatch
925954

@@ -1528,11 +1557,11 @@ def _get_inverse_paths_linestyles(self):
15281557
to nans to prevent drawing an inverse line.
15291558
"""
15301559
path_patterns = [
1531-
(mpath.Path(np.full((1, 2), np.nan)), ls)
1532-
if ls == (0, None) else
1533-
(path, mlines._get_inverse_dash_pattern(*ls))
1534-
for (path, ls) in
1535-
zip(self._paths, itertools.cycle(self._linestyles))]
1560+
(mpath.Path(np.full((1, 2), np.nan)), dash_patterns)
1561+
if dash_patterns == (0, None) else
1562+
(path, mlines._get_inverse_dash_pattern(*dash_patterns))
1563+
for (path, dash_patterns) in
1564+
zip(self._paths, itertools.cycle(self._dash_patterns))]
15361565

15371566
return zip(*path_patterns)
15381567

@@ -1555,7 +1584,7 @@ def __init__(self,
15551584
linelength=1,
15561585
linewidth=None,
15571586
color=None,
1558-
linestyle='solid',
1587+
linestyle='-',
15591588
antialiased=None,
15601589
**kwargs
15611590
):
@@ -1578,14 +1607,8 @@ def __init__(self,
15781607
The line width of the event lines, in points.
15791608
color : color or list of colors, default: :rc:`lines.color`
15801609
The color of the event lines.
1581-
linestyle : str or tuple or list thereof, default: 'solid'
1582-
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
1583-
'-', '--', '-.', ':']. Dash tuples should be of the form::
1584-
1585-
(offset, onoffseq),
1586-
1587-
where *onoffseq* is an even length tuple of on and off ink
1588-
in points.
1610+
linestyle : str or tuple or list thereof, default: '-'
1611+
Line style or list of line styles. See `set_linestyle` for details.
15891612
antialiased : bool or list thereof, default: :rc:`lines.antialiased`
15901613
Whether to use antialiasing for drawing the lines.
15911614
**kwargs

‎lib/matplotlib/collections.pyi

Copy file name to clipboardExpand all lines: lib/matplotlib/collections.pyi
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import numpy as np
1111
from numpy.typing import ArrayLike
1212
from collections.abc import Callable, Iterable, Sequence
1313
from typing import Literal
14-
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
14+
from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType, DashPatternType
1515

1616
class Collection(artist.Artist, cm.ScalarMappable):
1717
def __init__(
@@ -63,6 +63,7 @@ class Collection(artist.Artist, cm.ScalarMappable):
6363
def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ...
6464
def get_linewidth(self) -> float | Sequence[float]: ...
6565
def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ...
66+
def get_dashes(self) -> DashPatternType | Sequence[DashPatternType]: ...
6667
def update_scalarmappable(self) -> None: ...
6768
def get_fill(self) -> bool: ...
6869
def update_from(self, other: Artist) -> None: ...

‎lib/matplotlib/contour.py

Copy file name to clipboardExpand all lines: lib/matplotlib/contour.py
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -954,7 +954,7 @@ def collections(self):
954954
fcs = self.get_facecolor()
955955
ecs = self.get_edgecolor()
956956
lws = self.get_linewidth()
957-
lss = self.get_linestyle()
957+
lss = self.get_dashes()
958958
self._old_style_split_collections = []
959959
for idx, path in enumerate(self._paths):
960960
pc = mcoll.PathCollection(
@@ -1041,7 +1041,7 @@ def legend_elements(self, variable_name='x', str_format=str):
10411041
[], [],
10421042
color=self.get_edgecolor()[idx],
10431043
linewidth=self.get_linewidths()[idx],
1044-
linestyle=self.get_linestyles()[idx],
1044+
linestyle=self.get_dashes()[idx],
10451045
))
10461046
labels.append(fr'${variable_name} = {str_format(level)}$')
10471047

@@ -1470,7 +1470,7 @@ def draw(self, renderer):
14701470
hatch=self.hatches[idx % len(self.hatches)],
14711471
array=[self.get_array()[idx]],
14721472
linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]],
1473-
linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]],
1473+
dashes=[self.get_dashes()[idx % len(self.get_dashes())]],
14741474
):
14751475
super().draw(renderer)
14761476

‎lib/matplotlib/legend_handler.py

Copy file name to clipboardExpand all lines: lib/matplotlib/legend_handler.py
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ def _create_line(orig_handle, width, height):
373373
# Unfilled StepPatch should show as a line
374374
legline = Line2D([0, width], [height/2, height/2],
375375
color=orig_handle.get_edgecolor(),
376-
linestyle=orig_handle.get_linestyle(),
376+
linestyle=orig_handle.get_dashes(),
377377
linewidth=orig_handle.get_linewidth(),
378378
)
379379

@@ -407,7 +407,7 @@ def get_numpoints(self, legend):
407407

408408
def _default_update_prop(self, legend_handle, orig_handle):
409409
lw = orig_handle.get_linewidths()[0]
410-
dashes = orig_handle._us_linestyles[0]
410+
dashes = orig_handle._unscaled_dash_patterns[0]
411411
color = orig_handle.get_colors()[0]
412412
legend_handle.set_color(color)
413413
legend_handle.set_linestyle(dashes)
@@ -713,7 +713,7 @@ def _copy_collection_props(self, legend_handle, orig_handle):
713713
`.Line2D` *legend_handle*.
714714
"""
715715
legend_handle.set_color(orig_handle.get_color()[0])
716-
legend_handle.set_linestyle(orig_handle.get_linestyle()[0])
716+
legend_handle.set_linestyle(orig_handle.get_dashes()[0])
717717

718718

719719
class HandlerTuple(HandlerBase):
@@ -798,7 +798,7 @@ def get_first(prop_array):
798798
legend_handle._hatch_color = orig_handle._hatch_color
799799
# Setters are fine for the remaining attributes.
800800
legend_handle.set_linewidth(get_first(orig_handle.get_linewidths()))
801-
legend_handle.set_linestyle(get_first(orig_handle.get_linestyles()))
801+
legend_handle.set_linestyle(get_first(orig_handle.get_dashes()))
802802
legend_handle.set_transform(get_first(orig_handle.get_transforms()))
803803
legend_handle.set_figure(orig_handle.get_figure())
804804
# Alpha is already taken into account by the color attributes.

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.