Skip to content

Commit 55bc9a1

Browse files
committed
ENH: Add which parameter to Axis.get_gridlines
`Axis.get_gridlines` previously returned only major gridlines, with no public way to get the minor gridlines. Downstream libraries (seaborn, gwpy, mpld3, ...) had to reach into the private `_minor_tick_kw` mapping to inspect minor grid state. Extend the signature to `get_gridlines(which='major')`, accepting `'major'`, `'minor'`, or `'both'` (matching the vocabulary of `Axis.grid` and `get_ticklabels`). The default of `'major'` keeps the existing behavior byte-for-byte. Closes #19021
1 parent 1cb6fe2 commit 55bc9a1

4 files changed

Lines changed: 108 additions & 6 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
``Axis.get_gridlines`` can return minor gridlines
2+
-------------------------------------------------
3+
`~matplotlib.axis.Axis.get_gridlines` now accepts a *which* keyword argument
4+
to select major, minor, or both groups of gridlines. The default value
5+
``'major'`` preserves the previous behavior.
6+
7+
.. plot::
8+
:include-source: true
9+
:alt: Highlight every minor gridline of the x-axis in red.
10+
11+
import matplotlib.pyplot as plt
12+
13+
fig, ax = plt.subplots()
14+
ax.plot(range(10))
15+
ax.minorticks_on()
16+
ax.grid(which='both')
17+
18+
for line in ax.xaxis.get_gridlines(which='minor'):
19+
line.set_color('red')
20+
21+
plt.show()
22+
23+
Previously there was no public API to access minor gridlines, so downstream
24+
libraries reached into the private ``Axis._minor_tick_kw`` mapping to detect
25+
their state.

lib/matplotlib/axis.py

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,11 +1470,39 @@ def draw(self, renderer):
14701470
renderer.close_group(__name__)
14711471
self.stale = False
14721472

1473-
def get_gridlines(self):
1474-
r"""Return this Axis' grid lines as a list of `.Line2D`\s."""
1475-
ticks = self.get_major_ticks()
1476-
return cbook.silent_list('Line2D gridline',
1477-
[tick.gridline for tick in ticks])
1473+
def get_gridlines(self, which='major'):
1474+
r"""
1475+
Return this Axis' grid lines as a list of `.Line2D`\s.
1476+
1477+
Parameters
1478+
----------
1479+
which : {'major', 'minor', 'both'}, default: 'major'
1480+
Which set of gridlines to return.
1481+
1482+
.. versionchanged:: 3.11
1483+
Added the *which* parameter; previously only major gridlines
1484+
were returned.
1485+
1486+
Returns
1487+
-------
1488+
list of `.Line2D`
1489+
The gridline `.Line2D` objects. For ``which='both'``, major
1490+
gridlines come before minor gridlines.
1491+
1492+
Notes
1493+
-----
1494+
The returned list contains every gridline managed by this Axis
1495+
regardless of its visibility. Use ``Line2D.get_visible()`` on each
1496+
returned object to check whether a particular gridline is currently
1497+
drawn.
1498+
"""
1499+
_api.check_in_list(['major', 'minor', 'both'], which=which)
1500+
lines = []
1501+
if which in ('major', 'both'):
1502+
lines.extend(tick.gridline for tick in self.get_major_ticks())
1503+
if which in ('minor', 'both'):
1504+
lines.extend(tick.gridline for tick in self.get_minor_ticks())
1505+
return cbook.silent_list('Line2D gridline', lines)
14781506

14791507
def set_label(self, s):
14801508
"""Assigning legend labels is not supported. Raises RuntimeError."""

lib/matplotlib/axis.pyi

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,9 @@ class Axis(martist.Artist):
176176
self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ...
177177
) -> Bbox | None: ...
178178
def get_tick_padding(self) -> float: ...
179-
def get_gridlines(self) -> list[Line2D]: ...
179+
def get_gridlines(
180+
self, which: Literal["major", "minor", "both"] = ...
181+
) -> list[Line2D]: ...
180182
def get_label(self) -> Text: ...
181183
def get_offset_text(self) -> Text: ...
182184
def get_pickradius(self) -> float: ...

lib/matplotlib/tests/test_axes.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6300,6 +6300,53 @@ def test_grid():
63006300
assert not ax.xaxis.majorTicks[0].gridline.get_visible()
63016301

63026302

6303+
def test_get_gridlines_which():
6304+
"""`Axis.get_gridlines` selects major, minor, or both via *which*."""
6305+
fig, ax = plt.subplots()
6306+
ax.minorticks_on()
6307+
6308+
n_major = len(ax.xaxis.get_major_ticks())
6309+
n_minor = len(ax.xaxis.get_minor_ticks())
6310+
6311+
major_lines = ax.xaxis.get_gridlines()
6312+
assert len(major_lines) == n_major
6313+
assert major_lines == ax.xaxis.get_gridlines(which='major')
6314+
6315+
minor_lines = ax.xaxis.get_gridlines(which='minor')
6316+
assert len(minor_lines) == n_minor
6317+
assert all(line not in major_lines for line in minor_lines)
6318+
6319+
both_lines = ax.xaxis.get_gridlines(which='both')
6320+
assert len(both_lines) == n_major + n_minor
6321+
assert both_lines[:n_major] == major_lines
6322+
assert both_lines[n_major:] == minor_lines
6323+
6324+
with pytest.raises(ValueError, match="'which' must be in"):
6325+
ax.xaxis.get_gridlines(which='invalid')
6326+
6327+
6328+
def test_get_gridlines_visibility_reflects_grid_state():
6329+
"""Visibility of returned gridlines tracks the active grid state."""
6330+
fig, ax = plt.subplots()
6331+
ax.minorticks_on()
6332+
6333+
ax.grid(visible=False, which='both')
6334+
fig.canvas.draw()
6335+
assert not any(line.get_visible()
6336+
for line in ax.xaxis.get_gridlines(which='both'))
6337+
6338+
ax.grid(visible=True, which='major')
6339+
fig.canvas.draw()
6340+
assert all(line.get_visible() for line in ax.xaxis.get_gridlines('major'))
6341+
assert not any(line.get_visible()
6342+
for line in ax.xaxis.get_gridlines('minor'))
6343+
6344+
ax.grid(visible=True, which='minor')
6345+
fig.canvas.draw()
6346+
assert all(line.get_visible()
6347+
for line in ax.xaxis.get_gridlines(which='both'))
6348+
6349+
63036350
def test_grid_color_with_alpha():
63046351
"""Test that grid(color=(..., alpha)) respects the alpha value."""
63056352
fig, ax = plt.subplots()

0 commit comments

Comments
 (0)