Created
April 11, 2026 00:33
-
-
Save ejdanderson/7d11cc4fcc2c322e2ec8664abf54f0e7 to your computer and use it in GitHub Desktop.
Decouple Hatch Color and Edge Color Matplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as mpatches | |
| def hatch_bar(ax, x, y, hatch='///', hatch_color='blue', | |
| edge_color='black', lw=1.5, **kwargs): | |
| bars = ax.bar( | |
| x, y, | |
| facecolor='white', | |
| edgecolor=hatch_color, | |
| hatch=hatch, | |
| linewidth=0, | |
| **kwargs | |
| ) | |
| for bar in bars: | |
| ax.add_patch( | |
| mpatches.Rectangle( | |
| (bar.get_x(), bar.get_y()), | |
| bar.get_width(), | |
| bar.get_height(), | |
| fill=False, | |
| edgecolor=edge_color, | |
| linewidth=lw | |
| ) | |
| ) | |
| return bars | |
| def hatch_legend(label, hatch='///', hatch_color='blue'): | |
| return mpatches.Patch( | |
| facecolor='white', | |
| edgecolor=hatch_color, | |
| hatch=hatch, | |
| label=label | |
| ) | |
| x = [1, 2, 3] | |
| y = [3, 5, 2] | |
| ax = plt.gca() | |
| bars = ax.bar( | |
| x, y, | |
| facecolor='white', | |
| edgecolor='blue', # <-- hatch color | |
| hatch='///', | |
| linewidth=0 # hide default border | |
| ) | |
| # Add a separate border layer (black outline) | |
| for bar in bars: | |
| ax.add_patch( | |
| mpatches.Rectangle( | |
| (bar.get_x(), bar.get_y()), | |
| bar.get_width(), | |
| bar.get_height(), | |
| fill=False, | |
| edgecolor='black', | |
| linewidth=1.5 | |
| ) | |
| ) | |
| # --- Legend that matches hatch layer exactly --- | |
| legend_patch = mpatches.Patch( | |
| facecolor='white', | |
| edgecolor='blue', # hatch color | |
| hatch='///', | |
| label='My Data' | |
| ) | |
| ax.legend(handles=[legend_patch]) | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment