Skip to content

Commit c18140c

Browse files
committed
FIX: do dash scaling early
When scaling the dash pattern by the linewidth do the scaling at artist creation / value set time rather than at draw time. closes matplotlib#6592
1 parent b23460b commit c18140c

5 files changed

Lines changed: 142 additions & 82 deletions

File tree

‎lib/matplotlib/backend_bases.py‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -871,16 +871,7 @@ def get_dashes(self):
871871
872872
Default value is None
873873
"""
874-
if rcParams['_internal.classic_mode']:
875-
return self._dashes
876-
else:
877-
scale = max(1.0, self.get_linewidth())
878-
offset, dashes = self._dashes
879-
if offset is not None:
880-
offset = offset * scale
881-
if dashes is not None:
882-
dashes = [x * scale for x in dashes]
883-
return offset, dashes
874+
return self._dashes
884875

885876
def get_forced_alpha(self):
886877
"""
@@ -1062,10 +1053,7 @@ def set_linestyle(self, style):
10621053
`lines.dotted_pattern`. One may also specify customized dash
10631054
styles by providing a tuple of (offset, dash pairs).
10641055
"""
1065-
offset, dashes = lines.get_dash_pattern(style)
1066-
10671056
self._linestyle = style
1068-
self.set_dashes(offset, dashes)
10691057

10701058
def set_url(self, url):
10711059
"""

‎lib/matplotlib/collections.py‎

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,16 @@
1313

1414
import six
1515
from six.moves import zip
16+
try:
17+
from math import gcd
18+
except ImportError:
19+
# LPy workaround
20+
from fractions import gcd
1621
import warnings
22+
1723
import numpy as np
1824
import numpy.ma as ma
25+
1926
import matplotlib as mpl
2027
import matplotlib.cbook as cbook
2128
import matplotlib.colors as mcolors
@@ -24,13 +31,11 @@
2431
import matplotlib.transforms as transforms
2532
import matplotlib.artist as artist
2633
from matplotlib.artist import allow_rasterization
27-
import matplotlib.backend_bases as backend_bases
2834
import matplotlib.path as mpath
2935
from matplotlib import _path
3036
import matplotlib.mlab as mlab
3137
import matplotlib.lines as mlines
3238

33-
3439
CIRCLE_AREA_FACTOR = 1.0 / np.sqrt(np.pi)
3540

3641

@@ -117,7 +122,10 @@ def __init__(self,
117122
"""
118123
artist.Artist.__init__(self)
119124
cm.ScalarMappable.__init__(self, norm, cmap)
120-
125+
self._us_linestyles = [(None, None)]
126+
self._linestyles = [(None, None)]
127+
self._us_lw = [0]
128+
self._linewidths = [0]
121129
self.set_edgecolor(edgecolors)
122130
self.set_facecolor(facecolors)
123131
self.set_linewidth(linewidths)
@@ -313,7 +321,7 @@ def draw(self, renderer):
313321
if do_single_path_optimization:
314322
gc.set_foreground(tuple(edgecolors[0]))
315323
gc.set_linewidth(self._linewidths[0])
316-
gc.set_linestyle(self._linestyles[0])
324+
gc.set_dashes(*self._linestyles[0])
317325
gc.set_antialiased(self._antialiaseds[0])
318326
gc.set_url(self._urls[0])
319327
renderer.draw_markers(
@@ -489,8 +497,10 @@ def set_linewidth(self, lw):
489497
lw = mpl.rcParams['lines.linewidth']
490498
else:
491499
lw = 0
500+
self._us_lw = self._get_value(lw)
492501

493-
self._linewidths = self._get_value(lw)
502+
self._linewidths, self._linestyles = self._bcast_lwls(
503+
self._us_lw, self._us_linestyles)
494504
self.stale = True
495505

496506
def set_linewidths(self, lw):
@@ -534,29 +544,40 @@ def set_linestyle(self, ls):
534544
try:
535545
if cbook.is_string_like(ls) and cbook.is_hashable(ls):
536546
ls = cbook.ls_mapper.get(ls, ls)
537-
dashes = [mlines.get_dash_pattern(ls)]
538-
elif cbook.iterable(ls):
547+
dashes = [mlines._get_dash_pattern(ls)]
548+
else:
539549
try:
540-
dashes = []
541-
for x in ls:
542-
if cbook.is_string_like(x):
543-
x = cbook.ls_mapper.get(x, x)
544-
dashes.append(mlines.get_dash_pattern(x))
545-
elif cbook.iterable(x) and len(x) == 2:
546-
dashes.append(x)
547-
else:
548-
raise ValueError()
550+
dashes = [mlines._get_dash_pattern(ls)]
549551
except ValueError:
550-
if len(ls) == 2:
551-
dashes = [ls]
552-
else:
553-
raise ValueError()
554-
else:
555-
raise ValueError()
552+
dashes = [mlines._get_dash_pattern(x) for x in ls]
553+
556554
except ValueError:
557-
raise ValueError('Do not know how to convert %s to dashes' % ls)
558-
self._linestyles = dashes
559-
self.stale = True
555+
raise ValueError(
556+
'Do not know how to convert {!r} to dashes'.format(ls))
557+
558+
self._us_linestyles = dashes
559+
560+
self._linewidths, self._linestyles = self._bcast_lwls(
561+
self._us_lw, self._us_linestyles)
562+
563+
@staticmethod
564+
def _bcast_lwls(linewidths, dashes):
565+
if mpl.rcParams['_internal.classic_mode']:
566+
return linewidths, dashes
567+
# same length, we can just zip them
568+
if len(dashes) != len(linewidths):
569+
l_dashes = len(dashes)
570+
l_lw = len(linewidths)
571+
GCD = gcd(l_dashes, l_lw)
572+
dashes = list(dashes) * (l_lw // GCD)
573+
linewidths = list(linewidths) * (l_dashes // GCD)
574+
575+
# pass in None as first arg as collection do not
576+
# support offset in linestyles (yet)
577+
dashes = [mlines._scale_dashes(o, d, lw)
578+
for (o, d), lw in zip(dashes, linewidths)]
579+
580+
return linewidths, dashes
560581

561582
def set_linestyles(self, ls):
562583
"""alias for set_linestyle"""

‎lib/matplotlib/lines.py‎

Lines changed: 68 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313

1414
import numpy as np
1515
from numpy import ma
16-
from matplotlib import verbose
1716
from . import artist, colors as mcolors
1817
from .artist import Artist
1918
from .cbook import (iterable, is_string_like, is_numlike, ls_mapper_r,
20-
pts_to_prestep, pts_to_poststep, pts_to_midstep)
19+
pts_to_prestep, pts_to_poststep, pts_to_midstep, ls_mapper,
20+
is_hashable)
2121

2222
from .path import Path
2323
from .transforms import Bbox, TransformedPath, IdentityTransform
@@ -36,24 +36,47 @@
3636
from matplotlib import _path
3737

3838

39-
def get_dash_pattern(style):
40-
"""
41-
Given a dash pattern name from 'solid', 'dashed', 'dashdot' or
42-
'dotted', returns the (offset, dashes) pattern.
39+
def _get_dash_pattern(style):
40+
"""Convert linestyle -> dash pattern
41+
4342
"""
44-
if style == 'solid':
43+
# go from short hand -> full strings
44+
if is_string_like(style) and is_hashable(style):
45+
style = ls_mapper.get(style, style)
46+
# un-dashed styles
47+
if style in ['solid', 'None']:
4548
offset, dashes = None, None
49+
# dashed styles
4650
elif style in ['dashed', 'dashdot', 'dotted']:
4751
offset = 0
4852
dashes = tuple(rcParams['lines.{}_pattern'.format(style)])
53+
#
4954
elif isinstance(style, tuple):
5055
offset, dashes = style
5156
else:
5257
raise ValueError('Unrecognized linestyle: %s' % str(style))
5358

59+
# normalize offset to be positive and shorter than the dash cycle
60+
if dashes is not None and offset is not None:
61+
offset %= sum(dashes)
62+
5463
return offset, dashes
5564

5665

66+
def _scale_dashes(offset, dashes, lw):
67+
if rcParams['_internal.classic_mode']:
68+
return offset, dashes
69+
scale = max(1.0, lw)
70+
scaled_offset = scaled_dashes = None
71+
if offset is not None:
72+
scaled_offset = offset * scale
73+
if dashes is not None:
74+
scaled_dashes = [x * scale if x is not None else None
75+
for x in dashes]
76+
77+
return scaled_offset, scaled_dashes
78+
79+
5780
def segment_hits(cx, cy, x, y, radius):
5881
"""
5982
Determine if any line segments are within radius of a
@@ -360,10 +383,14 @@ def __init__(self, xdata, ydata,
360383

361384
self._linestyles = None
362385
self._drawstyle = None
363-
self._linewidth = None
386+
self._linewidth = linewidth
364387

388+
# scaled dash + offset
365389
self._dashSeq = None
366390
self._dashOffset = 0
391+
# unscaled dash + offset
392+
self._us_dashSeq = None
393+
self._us_dashOffset = 0
367394

368395
self.set_linestyle(linestyle)
369396
self.set_drawstyle(drawstyle)
@@ -1013,9 +1040,13 @@ def set_linewidth(self, w):
10131040
ACCEPTS: float value in points
10141041
"""
10151042
w = float(w)
1043+
10161044
if self._linewidth != w:
10171045
self.stale = True
10181046
self._linewidth = w
1047+
# rescale the dashes + offset
1048+
self._dashOffset, self._dashSeq = _scale_dashes(
1049+
self._us_dashOffset, self._us_dashSeq, self._linewidth)
10191050

10201051
def _split_drawstyle_linestyle(self, ls):
10211052
'''Split drawstyle from linestyle string
@@ -1093,31 +1124,31 @@ def set_linestyle(self, ls):
10931124
ls : { ``'-'``, ``'--'``, ``'-.'``, ``':'``} and more see description
10941125
The line style.
10951126
"""
1096-
if not is_string_like(ls):
1097-
if len(ls) != 2:
1098-
raise ValueError()
1099-
1100-
self.set_dashes(ls[1])
1101-
self._dashOffset = ls[0]
1102-
self._linestyle = "--"
1103-
return
1104-
ds, ls = self._split_drawstyle_linestyle(ls)
1105-
if ds is not None:
1106-
self.set_drawstyle(ds)
1107-
1108-
if ls in [' ', '', 'none']:
1109-
ls = 'None'
1110-
1111-
if ls not in self._lineStyles:
1112-
try:
1113-
ls = ls_mapper_r[ls]
1114-
except KeyError:
1115-
raise ValueError(("You passed in an invalid linestyle, "
1116-
"`{0}`. See "
1117-
"docs of Line2D.set_linestyle for "
1118-
"valid values.").format(ls))
1127+
if is_string_like(ls):
1128+
ds, ls = self._split_drawstyle_linestyle(ls)
1129+
if ds is not None:
1130+
self.set_drawstyle(ds)
1131+
1132+
if ls in [' ', '', 'none']:
1133+
ls = 'None'
1134+
1135+
if ls not in self._lineStyles:
1136+
try:
1137+
ls = ls_mapper_r[ls]
1138+
except KeyError:
1139+
raise ValueError(("You passed in an invalid linestyle, "
1140+
"`{0}`. See "
1141+
"docs of Line2D.set_linestyle for "
1142+
"valid values.").format(ls))
1143+
self._linestyle = ls
1144+
else:
1145+
self._linestyle = '--'
11191146

1120-
self._linestyle = ls
1147+
# get the unscaled dashes
1148+
self._us_dashOffset, self._us_dashSeq = _get_dash_pattern(ls)
1149+
# compute the linewidth scaled dashes
1150+
self._dashOffset, self._dashSeq = _scale_dashes(
1151+
self._us_dashOffset, self._us_dashSeq, self._linewidth)
11211152

11221153
@docstring.dedent_interpd
11231154
def set_marker(self, marker):
@@ -1227,10 +1258,7 @@ def set_dashes(self, seq):
12271258
if seq == (None, None) or len(seq) == 0:
12281259
self.set_linestyle('-')
12291260
else:
1230-
self.set_linestyle('--')
1231-
if self._dashSeq != seq:
1232-
self.stale = True
1233-
self._dashSeq = seq # TODO: offset ignored for now
1261+
self.set_linestyle((0, seq))
12341262

12351263
def _draw_lines(self, renderer, gc, path, trans):
12361264
self._lineFunc(renderer, gc, path, trans)
@@ -1258,21 +1286,22 @@ def _draw_steps_mid(self, renderer, gc, path, trans):
12581286

12591287
def _draw_solid(self, renderer, gc, path, trans):
12601288
gc.set_linestyle('solid')
1289+
gc.set_dashes(self._dashOffset, self._dashSeq)
12611290
renderer.draw_path(gc, path, trans)
12621291

12631292
def _draw_dashed(self, renderer, gc, path, trans):
12641293
gc.set_linestyle('dashed')
1265-
if self._dashSeq is not None:
1266-
gc.set_dashes(self._dashOffset, self._dashSeq)
1267-
1294+
gc.set_dashes(self._dashOffset, self._dashSeq)
12681295
renderer.draw_path(gc, path, trans)
12691296

12701297
def _draw_dash_dot(self, renderer, gc, path, trans):
12711298
gc.set_linestyle('dashdot')
1299+
gc.set_dashes(self._dashOffset, self._dashSeq)
12721300
renderer.draw_path(gc, path, trans)
12731301

12741302
def _draw_dotted(self, renderer, gc, path, trans):
12751303
gc.set_linestyle('dotted')
1304+
gc.set_dashes(self._dashOffset, self._dashSeq)
12761305
renderer.draw_path(gc, path, trans)
12771306

12781307
def update_from(self, other):

0 commit comments

Comments
 (0)