Skip to content

Instantly share code, notes, and snippets.

@Zulko
Created April 25, 2019 16:39
Show Gist options
  • Save Zulko/9c4e9b194529d6ee766e8a5937d96d87 to your computer and use it in GitHub Desktop.
Save Zulko/9c4e9b194529d6ee766e8a5937d96d87 to your computer and use it in GitHub Desktop.
Get complex matplotlib layouts by generating gridspac from a "layout array"
import numpy as np
from matplotlib.gridspec import GridSpec
def matplotlib_gridspecs_from_array(arr):
arr = np.array(arr)
h, w = arr.shape
values_in_arr = sorted(set(arr.flatten()))
result = []
grid = GridSpec(h, w)
for v in values_in_arr:
xx, yy = ((arr - v) == 0).nonzero()
result.append(grid[xx.min(): xx.max() + 1,
yy.min(): yy.max() + 1])
return result
def matplotlib_axes_from_gridspec_array(arr):
fig = plt.figure()
gridspecs = matplotlib_gridspecs_from_array(arr)
axes = []
for gridspec in gridspecs:
axes.append(fig.add_subplot(gridspec))
# Returns 3 axes layed out as indicated by the array
axes = matplotlib_axes_from_gridspec_array([
[1, 1, 3],
[2, 2, 3],
[2, 2, 3],
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment