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

Skip to content

Commit f6513e7

Browse files
committed
Fix Axes.grid() to respect alpha in color tuples
When calling ax.grid(color=(R, G, B, A)) with a 4-element color tuple, the alpha channel was being ignored, causing gridlines to appear fully opaque instead of with the specified transparency. The issue occurred in two locations: 1. Tick.__init__: When creating ticks, if grid_alpha was None but the color had an alpha channel, the alpha wasn't extracted from the color 2. Tick._apply_params: When updating gridlines via grid(), colors with alpha weren't being decomposed into separate color and alpha params This fix extracts the alpha value from color tuples using mcolors.to_rgba() and sets both the color (RGB only) and alpha separately, ensuring proper transparency rendering. Fixes matplotlib#22231
1 parent f1ea23f commit f6513e7

2 files changed

Lines changed: 45 additions & 11 deletions

File tree

lib/matplotlib/axis.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -140,17 +140,20 @@ def __init__(
140140
f"grid.{major_minor}.linewidth",
141141
"grid.linewidth",
142142
)
143-
if grid_alpha is None and not mcolors._has_alpha_channel(grid_color):
144-
# alpha precedence: kwarg > color alpha > rcParams['grid.alpha']
145-
# Note: only resolve to rcParams if the color does not have alpha
146-
# otherwise `grid(color=(1, 1, 1, 0.5))` would work like
147-
# grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha'])
148-
# so the that the rcParams default would override color alpha.
149-
grid_alpha = mpl._val_or_rc(
150-
# grid_alpha is None so we can use the first key
151-
mpl.rcParams[f"grid.{major_minor}.alpha"],
152-
"grid.alpha",
153-
)
143+
if grid_alpha is None:
144+
if mcolors._has_alpha_channel(grid_color):
145+
# Extract alpha from the color
146+
# alpha precedence: kwarg > color alpha > rcParams['grid.alpha']
147+
rgba = mcolors.to_rgba(grid_color)
148+
grid_color = rgba[:3] # RGB only
149+
grid_alpha = rgba[3] # Alpha from color
150+
else:
151+
# No alpha in color, use rcParams
152+
grid_alpha = mpl._val_or_rc(
153+
# grid_alpha is None so we can use the first key
154+
mpl.rcParams[f"grid.{major_minor}.alpha"],
155+
"grid.alpha",
156+
)
154157

155158
grid_kw = {k[5:]: v for k, v in kwargs.items() if k != "rotation_mode"}
156159

@@ -348,6 +351,15 @@ def _apply_params(self, **kwargs):
348351

349352
grid_kw = {k[5:]: v for k, v in kwargs.items()
350353
if k in _gridline_param_names}
354+
# If grid_color has an alpha channel and grid_alpha is not explicitly
355+
# set, extract the alpha from the color.
356+
if 'color' in grid_kw and 'alpha' not in grid_kw:
357+
grid_color = grid_kw['color']
358+
if mcolors._has_alpha_channel(grid_color):
359+
# Convert to rgba to extract alpha
360+
rgba = mcolors.to_rgba(grid_color)
361+
grid_kw['color'] = rgba[:3] # RGB only
362+
grid_kw['alpha'] = rgba[3] # Alpha channel
351363
self.gridline.set(**grid_kw)
352364

353365
def update_position(self, loc):

lib/matplotlib/tests/test_axes.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6133,6 +6133,28 @@ def test_grid():
61336133
assert not ax.xaxis.majorTicks[0].gridline.get_visible()
61346134

61356135

6136+
def test_grid_color_with_alpha():
6137+
"""Test that grid(color=(..., alpha)) respects the alpha value."""
6138+
fig, ax = plt.subplots()
6139+
ax.plot([0, 1], [0, 1])
6140+
6141+
# Test 1: Color tuple with alpha
6142+
ax.grid(True, color=(0.5, 0.6, 0.7, 0.3))
6143+
fig.canvas.draw()
6144+
6145+
# Check that alpha is extracted from color tuple
6146+
for tick in ax.xaxis.get_major_ticks():
6147+
assert tick.gridline.get_alpha() == 0.3, \
6148+
f"Expected alpha=0.3, got {tick.gridline.get_alpha()}"
6149+
# Color should be RGB only, without alpha component
6150+
color = tick.gridline.get_color()
6151+
assert len(color) in (3, 4), f"Unexpected color format: {color}"
6152+
6153+
for tick in ax.yaxis.get_major_ticks():
6154+
assert tick.gridline.get_alpha() == 0.3, \
6155+
f"Expected alpha=0.3, got {tick.gridline.get_alpha()}"
6156+
6157+
61366158
def test_reset_grid():
61376159
fig, ax = plt.subplots()
61386160
ax.tick_params(reset=True, which='major', labelsize=10)

0 commit comments

Comments
 (0)