Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bf9e17d

Browse files
committed
Backport PR matplotlib#18769: Support ax.grid(visible=<bool>).
1 parent f51e408 commit bf9e17d

File tree

4 files changed

+59
-49
lines changed

4 files changed

+59
-49
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2885,8 +2885,6 @@ def grid(self, b=None, which='major', axis='both', **kwargs):
28852885
use `.set_axisbelow` or, for more control, call the
28862886
`~.Artist.set_zorder` method of each axis.
28872887
"""
2888-
if len(kwargs):
2889-
b = True
28902888
cbook._check_in_list(['x', 'y', 'both'], axis=axis)
28912889
if axis in ['x', 'both']:
28922890
self.xaxis.grid(b, which=which, **kwargs)

lib/matplotlib/axis.py

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -778,10 +778,10 @@ def cla(self):
778778
self.callbacks = cbook.CallbackRegistry()
779779

780780
# whether the grids are on
781-
self._gridOnMajor = (
781+
self._major_tick_kw['gridOn'] = (
782782
mpl.rcParams['axes.grid'] and
783783
mpl.rcParams['axes.grid.which'] in ('both', 'major'))
784-
self._gridOnMinor = (
784+
self._minor_tick_kw['gridOn'] = (
785785
mpl.rcParams['axes.grid'] and
786786
mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
787787

@@ -1381,7 +1381,6 @@ def get_major_ticks(self, numticks=None):
13811381
# Update the new tick label properties from the old.
13821382
tick = self._get_tick(major=True)
13831383
self.majorTicks.append(tick)
1384-
tick.gridline.set_visible(self._gridOnMajor)
13851384
self._copy_tick_props(self.majorTicks[0], tick)
13861385

13871386
return self.majorTicks[:numticks]
@@ -1395,7 +1394,6 @@ def get_minor_ticks(self, numticks=None):
13951394
# Update the new tick label properties from the old.
13961395
tick = self._get_tick(major=False)
13971396
self.minorTicks.append(tick)
1398-
tick.gridline.set_visible(self._gridOnMinor)
13991397
self._copy_tick_props(self.minorTicks[0], tick)
14001398

14011399
return self.minorTicks[:numticks]
@@ -1420,32 +1418,37 @@ def grid(self, b=None, which='major', **kwargs):
14201418
Define the line properties of the grid, e.g.::
14211419
14221420
grid(color='r', linestyle='-', linewidth=2)
1423-
14241421
"""
1425-
if len(kwargs):
1426-
if not b and b is not None: # something false-like but not None
1422+
if b is not None:
1423+
if 'visible' in kwargs and bool(b) != bool(kwargs['visible']):
1424+
raise ValueError(
1425+
"'b' and 'visible' specify inconsistent grid visibilities")
1426+
if kwargs and not b: # something false-like but not None
14271427
cbook._warn_external('First parameter to grid() is false, '
14281428
'but line properties are supplied. The '
14291429
'grid will be enabled.')
1430-
b = True
1430+
b = True
14311431
which = which.lower()
14321432
cbook._check_in_list(['major', 'minor', 'both'], which=which)
14331433
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
1434+
if 'grid_visible' in gridkw:
1435+
forced_visibility = True
1436+
gridkw['gridOn'] = gridkw.pop('grid_visible')
1437+
else:
1438+
forced_visibility = False
14341439

14351440
if which in ['minor', 'both']:
1436-
if b is None:
1437-
self._gridOnMinor = not self._gridOnMinor
1438-
else:
1439-
self._gridOnMinor = b
1440-
self.set_tick_params(which='minor', gridOn=self._gridOnMinor,
1441-
**gridkw)
1441+
if b is None and not forced_visibility:
1442+
gridkw['gridOn'] = not self._minor_tick_kw['gridOn']
1443+
elif b is not None:
1444+
gridkw['gridOn'] = b
1445+
self.set_tick_params(which='minor', **gridkw)
14421446
if which in ['major', 'both']:
1443-
if b is None:
1444-
self._gridOnMajor = not self._gridOnMajor
1445-
else:
1446-
self._gridOnMajor = b
1447-
self.set_tick_params(which='major', gridOn=self._gridOnMajor,
1448-
**gridkw)
1447+
if b is None and not forced_visibility:
1448+
gridkw['gridOn'] = not self._major_tick_kw['gridOn']
1449+
elif b is not None:
1450+
gridkw['gridOn'] = b
1451+
self.set_tick_params(which='major', **gridkw)
14491452
self.stale = True
14501453

14511454
def update_units(self, data):

lib/matplotlib/tests/test_axes.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4310,26 +4310,35 @@ def test_twin_spines_on_top():
43104310
ax2.fill_between("i", "j", color='#7FC97F', alpha=.5, data=data)
43114311

43124312

4313-
def test_rcparam_grid_minor():
4314-
orig_grid = matplotlib.rcParams['axes.grid']
4315-
orig_locator = matplotlib.rcParams['axes.grid.which']
4316-
4317-
matplotlib.rcParams['axes.grid'] = True
4318-
4319-
values = (
4320-
(('both'), (True, True)),
4321-
(('major'), (True, False)),
4322-
(('minor'), (False, True))
4323-
)
4313+
@pytest.mark.parametrize("grid_which, major_visible, minor_visible", [
4314+
("both", True, True),
4315+
("major", True, False),
4316+
("minor", False, True),
4317+
])
4318+
def test_rcparam_grid_minor(grid_which, major_visible, minor_visible):
4319+
mpl.rcParams.update({"axes.grid": True, "axes.grid.which": grid_which})
4320+
fig, ax = plt.subplots()
4321+
fig.canvas.draw()
4322+
assert all(tick.gridline.get_visible() == major_visible
4323+
for tick in ax.xaxis.majorTicks)
4324+
assert all(tick.gridline.get_visible() == minor_visible
4325+
for tick in ax.xaxis.minorTicks)
43244326

4325-
for locator, result in values:
4326-
matplotlib.rcParams['axes.grid.which'] = locator
4327-
fig = plt.figure()
4328-
ax = fig.add_subplot(1, 1, 1)
4329-
assert (ax.xaxis._gridOnMajor, ax.xaxis._gridOnMinor) == result
43304327

4331-
matplotlib.rcParams['axes.grid'] = orig_grid
4332-
matplotlib.rcParams['axes.grid.which'] = orig_locator
4328+
def test_grid():
4329+
fig, ax = plt.subplots()
4330+
ax.grid()
4331+
fig.canvas.draw()
4332+
assert ax.xaxis.majorTicks[0].gridline.get_visible()
4333+
ax.grid(visible=False)
4334+
fig.canvas.draw()
4335+
assert not ax.xaxis.majorTicks[0].gridline.get_visible()
4336+
ax.grid(visible=True)
4337+
fig.canvas.draw()
4338+
assert ax.xaxis.majorTicks[0].gridline.get_visible()
4339+
ax.grid()
4340+
fig.canvas.draw()
4341+
assert not ax.xaxis.majorTicks[0].gridline.get_visible()
43334342

43344343

43354344
def test_vline_limit():

lib/mpl_toolkits/axisartist/axislines.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -439,9 +439,9 @@ def get_gridlines(self, which="major", axis="both"):
439439
if axis in ["both", "y"]:
440440
x1, x2 = self.axes.get_xlim()
441441
locs = []
442-
if self.axes.yaxis._gridOnMajor:
442+
if self.axes.yaxis._major_tick_kw["gridOn"]:
443443
locs.extend(self.axes.yaxis.major.locator())
444-
if self.axes.yaxis._gridOnMinor:
444+
if self.axes.yaxis._minor_tick_kw["gridOn"]:
445445
locs.extend(self.axes.yaxis.minor.locator())
446446

447447
for y in locs:
@@ -533,17 +533,17 @@ def grid(self, b=None, which='major', axis="both", **kwargs):
533533
"""
534534
Toggle the gridlines, and optionally set the properties of the lines.
535535
"""
536-
# their are some discrepancy between the behavior of grid in
537-
# axes_grid and the original mpl's grid, because axes_grid
538-
# explicitly set the visibility of the gridlines.
536+
# There are some discrepancies in the behavior of grid() between
537+
# axes_grid and Matplotlib, because axes_grid explicitly sets the
538+
# visibility of the gridlines.
539539
super().grid(b, which=which, axis=axis, **kwargs)
540540
if not self._axisline_on:
541541
return
542542
if b is None:
543-
b = (self.axes.xaxis._gridOnMinor
544-
or self.axes.xaxis._gridOnMajor
545-
or self.axes.yaxis._gridOnMinor
546-
or self.axes.yaxis._gridOnMajor)
543+
b = (self.axes.xaxis._minor_tick_kw["gridOn"]
544+
or self.axes.xaxis._major_tick_kw["gridOn"]
545+
or self.axes.yaxis._minor_tick_kw["gridOn"]
546+
or self.axes.yaxis._major_tick_kw["gridOn"])
547547
self.gridlines.set(which=which, axis=axis, visible=b)
548548
self.gridlines.set(**kwargs)
549549

0 commit comments

Comments
 (0)