Skip to content

Instantly share code, notes, and snippets.

@badge
Created September 18, 2020 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badge/d96aa245cf45efe737b4527b8d1c75d1 to your computer and use it in GitHub Desktop.
Save badge/d96aa245cf45efe737b4527b8d1c75d1 to your computer and use it in GitHub Desktop.
A friendlier matplotlib subplots implementation for multiple rows and/or columns
import math
import matplotlib.pyplot as plt
import scipy.signal.windows as windows
import inspect
from itertools import zip_longest
def better_subplots(
nrows=1,
ncols=1,
*,
sharex=False,
sharey=False,
squeeze=True,
subplot_kw=None,
gridspec_kw=None,
naxes=None,
axsize=None,
**fig_kw,
):
if naxes is not None:
if nrows == -1:
nrows = int(math.ceil(naxes / ncols))
elif ncols == -1:
ncols = int(math.ceil(naxes / nrows))
if axsize is not None:
(ax_width, ax_height) = axsize
fig_kw["figsize"] = (
ncols * ax_width,
nrows * ax_height
)
return plt.subplots(
nrows=nrows,
ncols=ncols,
sharex=sharex,
sharey=sharey,
squeeze=squeeze,
subplot_kw=subplot_kw,
gridspec_kw=gridspec_kw,
**fig_kw,
)
# Get the list of window functions whose only required parameter is named "M"
window_funcs = [
func
for func in dir(windows)
if callable(getattr(windows, func))
and not any(
(name, param)
for (name, param)
in inspect.signature(getattr(windows, func)).parameters.items()
if name != "M" and param.default == inspect._empty
)
]
fig, axes = better_subplots(nrows=-1, ncols=3, naxes=len(window_funcs), axsize=(3, 2), constrained_layout=True)
for func, ax in zip_longest(window_funcs, axes.flat):
if func is None:
ax.set_visible(False)
else:
ax.plot(getattr(windows, func)(51))
ax.set_title(func.title())
fig.suptitle("scipy.signal.windows Window Shapes")
@badge
Copy link
Author

badge commented Sep 18, 2020

index

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment