Skip to content

Conversation

@Nabeelshar
Copy link

PR summary

This PR fixes issue #22231 where ax.grid(color=(R, G, B, A)) ignores the alpha channel in color tuples, causing gridlines to appear fully opaque instead of with the specified transparency.

Problem: When calling ax.grid(color=(0.8, 0.8, 0.8, 0.2)), the gridlines appeared with alpha=1.0 instead of alpha=0.2.

Root Cause: The issue occurred in two places in lib/matplotlib/axis.py:

  1. Tick.__init__: When creating ticks with a color containing alpha, the code didn't extract the alpha value from the color tuple
  2. Tick._apply_params: When updating gridlines via grid(), color tuples with alpha weren't being decomposed

Solution: Extract alpha from color tuples using mcolors.to_rgba() and set color (RGB) and alpha separately, ensuring proper alpha precedence: explicit alpha parameter > color tuple alpha > rcParams.

Minimum example demonstrating the fix:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])
ax.grid(True, color=(0.8, 0.8, 0.8, 0.2))  # Alpha=0.2 now works!
plt.show()

closes #22231

PR checklist

  • "closes [Bug]: Axes.grid(color) ignores alpha #22231" is in the body of the PR description to link the related issue
  • new and changed code is tested (added test_grid_color_with_alpha)
  • [N/A] Plotting related features are demonstrated in an example (bug fix, not new feature)
  • [N/A] New Features and API Changes are noted with a directive and release note (bug fix, not API change)
  • Documentation complies with general and docstring guidelines (no docstring changes needed)

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Axes.grid(color) ignores alpha

1 participant