Skip to content
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

Enables setting hatch linewidth in Patches and Collections, also fixes setting hatch linewidth by rcParams #28048

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2dcaad7
Add hatch linewidth setter in Graphics Context Base
Impaler343 Apr 9, 2024
4711925
Add linewidth parameter to hatch style in PDF, PS and SVG backends
Impaler343 Apr 9, 2024
7d5cc53
Add linewidht setter and getter methods to Collections
Impaler343 Apr 9, 2024
ecd0065
Deprecation warning for setting linewidths in non-PDF,PS,SVG backends
Impaler343 Apr 9, 2024
76054d1
Add setter and getter methods for hatch linewidth in Patch
Impaler343 Apr 9, 2024
29237e7
Revert eps changes
Impaler343 Apr 9, 2024
a5214b4
Fix wrong linewidth get
Impaler343 Apr 9, 2024
afd25a1
Add linewidth in ps backend
Impaler343 Apr 9, 2024
9f843cb
Add type checks
Impaler343 Apr 9, 2024
1bfbbb2
Add test for patches setter and getter
Impaler343 Apr 10, 2024
2c6f829
Add test for collections setter and getter
Impaler343 Apr 10, 2024
e241caf
Fixed Collection test
Impaler343 Apr 11, 2024
206e1b2
Fix Collection test
Impaler343 Apr 11, 2024
3f8a483
Minor Changes
Impaler343 Apr 11, 2024
b0fd232
Moved _set_hatch_linewidth to backend_bases
Impaler343 Apr 11, 2024
3a05120
Delete _set_hatch_linewidth from hatch
Impaler343 Apr 11, 2024
93fa390
Change gc parameter position
Impaler343 Apr 11, 2024
ba00bf4
Removed _set_hatch_linewidth and pulled back unwanted changes
Impaler343 Apr 24, 2024
cf3d53f
Fix Indentation
Impaler343 May 8, 2024
10a5d52
Added API change note
Impaler343 May 12, 2024
6a98813
Test if commented lines are being used
Impaler343 Jun 6, 2024
7f0d0b8
Removed None conditions
Impaler343 Jun 6, 2024
c60a5bc
Added None check for face
Impaler343 Jun 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions doc/api/next_api_changes/deprecations/28048-PR.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
``PdfFile.hatchPatterns``
~~~~~~~~~~~~~~~~~~~~~~~~~

... is deprecated and replaced by an internal helper called ``PdfFile._hatch_patterns`` instead.

- The attribute ``PdfFile._hatch_patterns`` now stores hatch linewidths as well.
4 changes: 4 additions & 0 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,10 @@ def get_hatch_linewidth(self):
"""Get the hatch linewidth."""
return self._hatch_linewidth

def set_hatch_linewidth(self, hatch_linewidth):
"""Set the hatch linewidth - not supported on all backends."""
self._hatch_linewidth = hatch_linewidth

def get_sketch_params(self):
"""
Return the sketch parameters for the artist.
Expand Down
1 change: 1 addition & 0 deletions lib/matplotlib/backend_bases.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ class GraphicsContextBase:
def get_hatch_color(self) -> ColorType: ...
def set_hatch_color(self, hatch_color: ColorType) -> None: ...
def get_hatch_linewidth(self) -> float: ...
def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
def get_sketch_params(self) -> tuple[float, float, float] | None: ...
def set_sketch_params(
self,
Expand Down
44 changes: 23 additions & 21 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,7 @@ def __init__(self, filename, metadata=None):
self._soft_mask_states = {}
self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1))
self._soft_mask_groups = []
self.hatchPatterns = {}
self._hatch_patterns = {}
self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1))
self.gouraudTriangles = []

Expand Down Expand Up @@ -1534,26 +1534,28 @@ def _write_soft_mask_groups(self):

def hatchPattern(self, hatch_style):
# The colors may come in as numpy arrays, which aren't hashable
if hatch_style is not None:
edge, face, hatch = hatch_style
if edge is not None:
edge = tuple(edge)
if face is not None:
face = tuple(face)
hatch_style = (edge, face, hatch)

pattern = self.hatchPatterns.get(hatch_style, None)
edge, face, hatch, lw = hatch_style
edge = tuple(edge)
if face is not None:
face = tuple(face)
hatch_style = (edge, face, hatch, lw)

pattern = self._hatch_patterns.get(hatch_style, None)
if pattern is not None:
return pattern

name = next(self._hatch_pattern_seq)
self.hatchPatterns[hatch_style] = name
self._hatch_patterns[hatch_style] = name
return name

hatchPatterns = _api.deprecated("3.10")(property(lambda self: {
k: (e, f, h) for k, (e, f, h, l) in self._hatch_patterns.items()
}))

def writeHatches(self):
hatchDict = dict()
sidelen = 72.0
for hatch_style, name in self.hatchPatterns.items():
for hatch_style, name in self._hatch_patterns.items():
ob = self.reserveObject('hatch pattern')
hatchDict[name] = ob
res = {'Procsets':
Expand All @@ -1568,7 +1570,7 @@ def writeHatches(self):
# Change origin to match Agg at top-left.
'Matrix': [1, 0, 0, 1, 0, self.height * 72]})

stroke_rgb, fill_rgb, hatch = hatch_style
stroke_rgb, fill_rgb, hatch, lw = hatch_style
self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2],
Op.setrgb_stroke)
if fill_rgb is not None:
Expand All @@ -1577,7 +1579,7 @@ def writeHatches(self):
0, 0, sidelen, sidelen, Op.rectangle,
Op.fill)

self.output(mpl.rcParams['hatch.linewidth'], Op.setlinewidth)
self.output(lw, Op.setlinewidth)

self.output(*self.pathOperations(
Path.hatch(hatch),
Expand Down Expand Up @@ -2460,7 +2462,7 @@ def stroke(self):
"""
# _linewidth > 0: in pdf a line of width 0 is drawn at minimum
# possible device width, but e.g., agg doesn't draw at all
return (self._linewidth > 0 and self._alpha > 0 and
return (self.get_linewidth() > 0 and self._alpha > 0 and
(len(self._rgb) <= 3 or self._rgb[3] != 0.0))

def fill(self, *args):
Expand Down Expand Up @@ -2508,14 +2510,14 @@ def alpha_cmd(self, alpha, forced, effective_alphas):
name = self.file.alphaState(effective_alphas)
return [name, Op.setgstate]

def hatch_cmd(self, hatch, hatch_color):
def hatch_cmd(self, hatch, hatch_color, hatch_linewidth):
if not hatch:
if self._fillcolor is not None:
return self.fillcolor_cmd(self._fillcolor)
else:
return [Name('DeviceRGB'), Op.setcolorspace_nonstroke]
else:
hatch_style = (hatch_color, self._fillcolor, hatch)
hatch_style = (hatch_color, self._fillcolor, hatch, hatch_linewidth)
name = self.file.hatchPattern(hatch_style)
return [Name('Pattern'), Op.setcolorspace_nonstroke,
name, Op.setcolor_nonstroke]
Expand Down Expand Up @@ -2580,8 +2582,8 @@ def clip_cmd(self, cliprect, clippath):
(('_dashes',), dash_cmd),
(('_rgb',), rgb_cmd),
# must come after fillcolor and rgb
(('_hatch', '_hatch_color'), hatch_cmd),
)
(('_hatch', '_hatch_color', '_hatch_linewidth'), hatch_cmd),
)

def delta(self, other):
"""
Expand Down Expand Up @@ -2609,11 +2611,11 @@ def delta(self, other):
break

# Need to update hatching if we also updated fillcolor
if params == ('_hatch', '_hatch_color') and fill_performed:
if cmd.__name__ == 'hatch_cmd' and fill_performed:
different = True

if different:
if params == ('_fillcolor',):
if cmd.__name__ == 'fillcolor_cmd':
fill_performed = True
theirs = [getattr(other, p) for p in params]
cmds.extend(cmd(self, *theirs))
Expand Down
11 changes: 6 additions & 5 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,12 +344,12 @@ def set_font(self, fontname, fontsize, store=True):
self.fontname = fontname
self.fontsize = fontsize

def create_hatch(self, hatch):
def create_hatch(self, hatch, gc=None):
sidelen = 72
if hatch in self._hatches:
return self._hatches[hatch]
name = 'H%d' % len(self._hatches)
linewidth = mpl.rcParams['hatch.linewidth']
linewidth = gc.get_hatch_linewidth()
pageheight = self.height * 72
self._pswriter.write(f"""\
<< /PatternType 1
Expand All @@ -361,8 +361,9 @@ def create_hatch(self, hatch):

/PaintProc {{
pop
{linewidth:g} setlinewidth
{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
{linewidth:f} setlinewidth
{self._convert_path(
Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
Impaler343 marked this conversation as resolved.
Show resolved Hide resolved
gsave
fill
grestore
Expand Down Expand Up @@ -772,7 +773,7 @@ def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
write("grestore\n")

if hatch:
hatch_name = self.create_hatch(hatch)
hatch_name = self.create_hatch(hatch, gc)
write("gsave\n")
write(_nums_to_str(*gc.get_hatch_color()[:3]))
write(f" {hatch_name} setpattern fill grestore\n")
Expand Down
9 changes: 5 additions & 4 deletions lib/matplotlib/backends/backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,11 +484,12 @@ def _get_hatch(self, gc, rgbFace):
edge = gc.get_hatch_color()
if edge is not None:
edge = tuple(edge)
dictkey = (gc.get_hatch(), rgbFace, edge)
lw = gc._hatch_linewidth
dictkey = (gc.get_hatch(), rgbFace, edge, lw)
oid = self._hatchd.get(dictkey)
if oid is None:
oid = self._make_id('h', dictkey)
self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge), oid)
self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge, lw), oid)
else:
_, oid = oid
return oid
Expand All @@ -499,7 +500,7 @@ def _write_hatches(self):
HATCH_SIZE = 72
writer = self.writer
writer.start('defs')
for (path, face, stroke), oid in self._hatchd.values():
for (path, face, stroke, lw), oid in self._hatchd.values():
writer.start(
'pattern',
id=oid,
Expand All @@ -523,7 +524,7 @@ def _write_hatches(self):
hatch_style = {
'fill': rgb2hex(stroke),
'stroke': rgb2hex(stroke),
'stroke-width': str(mpl.rcParams['hatch.linewidth']),
'stroke-width': str(lw),
'stroke-linecap': 'butt',
'stroke-linejoin': 'miter'
}
Expand Down
10 changes: 10 additions & 0 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ def __init__(self, *,
self._edge_is_mapped = None
self._mapped_colors = None # calculated in update_scalarmappable
self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
self.set_facecolor(facecolors)
self.set_edgecolor(edgecolors)
self.set_linewidth(linewidths)
Expand Down Expand Up @@ -363,6 +364,7 @@ def draw(self, renderer):
if self._hatch:
gc.set_hatch(self._hatch)
gc.set_hatch_color(self._hatch_color)
gc.set_hatch_linewidth(self._hatch_linewidth)

if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
Expand Down Expand Up @@ -541,6 +543,14 @@ def get_hatch(self):
"""Return the current hatching pattern."""
return self._hatch

def set_hatch_linewidth(self, lw):
"""Set the hatch linewidth"""
self._hatch_linewidth = lw

def get_hatch_linewidth(self):
"""Return the hatch linewidth"""
return self._hatch_linewidth

def set_offsets(self, offsets):
"""
Set the offsets for the collection.
Expand Down
2 changes: 2 additions & 0 deletions lib/matplotlib/collections.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class Collection(artist.Artist, cm.ScalarMappable):
def get_urls(self) -> Sequence[str | None]: ...
def set_hatch(self, hatch: str) -> None: ...
def get_hatch(self) -> str: ...
def set_hatch_linewidth(self, lw: float) -> None: ...
def get_hatch_linewidth(self) -> float: ...
def set_offsets(self, offsets: ArrayLike) -> None: ...
def get_offsets(self) -> ArrayLike: ...
def set_linewidth(self, lw: float | Sequence[float]) -> None: ...
Expand Down
10 changes: 10 additions & 0 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def __init__(self, *,
joinstyle = JoinStyle.miter

self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
self._fill = bool(fill) # needed for set_facecolor call
if color is not None:
if edgecolor is not None or facecolor is not None:
Expand Down Expand Up @@ -571,6 +572,14 @@ def get_hatch(self):
"""Return the hatching pattern."""
return self._hatch

def set_hatch_linewidth(self, hatch_linewidth):
"""Set the hatch linewidth"""
self._hatch_linewidth = hatch_linewidth

def get_hatch_linewidth(self):
"""Return the hatch linewidth"""
return self._hatch_linewidth

def _draw_paths_with_artist_properties(
self, renderer, draw_path_args_list):
"""
Expand Down Expand Up @@ -605,6 +614,7 @@ def _draw_paths_with_artist_properties(
if self._hatch:
gc.set_hatch(self._hatch)
gc.set_hatch_color(self._hatch_color)
gc.set_hatch_linewidth(self._hatch_linewidth)

if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
Expand Down
2 changes: 2 additions & 0 deletions lib/matplotlib/patches.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ class Patch(artist.Artist):
def set_joinstyle(self, s: JoinStyleType) -> None: ...
def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
def set_hatch(self, hatch: str) -> None: ...
def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
def get_hatch_linewidth(self) -> float: ...
def get_hatch(self) -> str: ...
def get_path(self) -> Path: ...

Expand Down
24 changes: 24 additions & 0 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1336,3 +1336,27 @@ def test_striped_lines(fig_test, fig_ref, gapcolor):
for x, gcol, ls in zip(x, itertools.cycle(gapcolor),
itertools.cycle(linestyles)):
ax_ref.axvline(x, 0, 1, linestyle=ls, gapcolor=gcol, alpha=0.5)


@check_figures_equal(extensions=["png", "pdf", "svg", "eps"])
def test_hatch_linewidth(fig_test, fig_ref):
Impaler343 marked this conversation as resolved.
Show resolved Hide resolved
ax_test = fig_test.add_subplot()
ax_ref = fig_ref.add_subplot()

lw = 2.0

polygons = [
[(0.1, 0.1), (0.1, 0.4), (0.4, 0.4), (0.4, 0.1)],
[(0.6, 0.6), (0.6, 0.9), (0.9, 0.9), (0.9, 0.6)]
]
ref = PolyCollection(polygons, hatch="x")
ref.set_hatch_linewidth(lw)

with mpl.rc_context({"hatch.linewidth": lw}):
test = PolyCollection(polygons, hatch="x")
test.set_hatch_linewidth(lw)

ax_ref.add_collection(ref)
ax_test.add_collection(test)

assert (test.get_hatch_linewidth() == lw) and (ref.get_hatch_linewidth() == lw)
17 changes: 17 additions & 0 deletions lib/matplotlib/tests/test_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,3 +960,20 @@ def test_arrow_set_data():
)
arrow.set_data(x=.5, dx=3, dy=8, width=1.2)
assert np.allclose(expected2, np.round(arrow.get_verts(), 2))


@check_figures_equal(extensions=["png", "pdf", "svg", "eps"])
def test_set_and_get_hatch_linewidth(fig_test, fig_ref):
ax_test = fig_test.add_subplot()
ax_ref = fig_ref.add_subplot()

lw = 2.0

with plt.rc_context({"hatch.linewidth": lw}):
ax_ref.add_patch(mpatches.Rectangle((0, 0), 1, 1, hatch="x"))

ax_test.add_patch(mpatches.Rectangle((0, 0), 1, 1, hatch="x"))
ax_test.patches[0].set_hatch_linewidth(lw)

assert (ax_ref.patches[0].get_hatch_linewidth() == lw)
assert (ax_test.patches[0].get_hatch_linewidth() == lw)