Created
April 20, 2022 20:35
-
-
Save scottstanie/dff0d597e636440fb60b3c5443f70cae to your computer and use it in GitHub Desktop.
Add a zebra (nautical) frame to matplotlib cartopy plot
This file contains 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 itertools | |
import matplotlib.patheffects as pe | |
import numpy as np | |
def add_zebra_frame(ax, lw=2, crs="pcarree", zorder=None): | |
ax.spines["geo"].set_visible(False) | |
left, right, bot, top = ax.get_extent() | |
# Alternate black and white line segments | |
bws = itertools.cycle(["k", "white"]) | |
xticks = sorted([left, *ax.get_xticks(), right]) | |
xticks = np.unique(np.array(xticks)) | |
yticks = sorted([bot, *ax.get_yticks(), top]) | |
yticks = np.unique(np.array(yticks)) | |
for ticks, which in zip([xticks, yticks], ["lon", "lat"]): | |
for idx, (start, end) in enumerate(zip(ticks, ticks[1:])): | |
bw = next(bws) | |
if which == "lon": | |
xs = [[start, end], [start, end]] | |
ys = [[bot, bot], [top, top]] | |
else: | |
xs = [[left, left], [right, right]] | |
ys = [[start, end], [start, end]] | |
# For first and lastlines, used the "projecting" effect | |
capstyle = "butt" if idx not in (0, len(ticks) - 2) else "projecting" | |
for (xx, yy) in zip(xs, ys): | |
ax.plot( | |
xx, | |
yy, | |
color=bw, | |
linewidth=lw, | |
clip_on=False, | |
transform=crs, | |
zorder=zorder, | |
solid_capstyle=capstyle, | |
# Add a black border to accentuate white segments | |
path_effects=[ | |
pe.Stroke(linewidth=lw + 1, foreground="black"), | |
pe.Normal(), | |
], | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment