Reputation: 21
I want to make a plot that has 2x2 outer layout and within each one of these 2x3 layouts. I managed to get everything working using gridSpec, but I cannot seem to assign a title for each one of subplotSpec (there are 2x2 subplotSpec).
Row titles for matplotlib subplot This in principle should give me the solution, but I want to know if there are ways to achieve this using gridSpec and not hiding the white frame.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
netdict = ["chain","V"]
sigdict = ["no","with"]
fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.3, hspace=0.3) # make a 2x2 outer frame
for ni, networktype in enumerate(netdict):
for si, sigtype in enumerate(sigdict):
fig.add_subplot(outer[ni*2+si])
plt.title(networktype+ " " + sigtype) # title for each outer frame
plt._frameon=False # this should make the unnecessary white frame go away
inner = gridspec.GridSpecFromSubplotSpec(2, 3, # make 2x3 inner frame
subplot_spec=outer[ni*2+si], wspace=0.4, hspace=0.4)
for ti,tau in enumerate([5.5,12.5]):
for u, xy_delay in enumerate([0,tau,2*tau]):
ax = plt.Subplot(fig, inner[ti*3+u])
ax.plot(np.sin(np.linspace(0,10,0.5))
ax.set(title=r"$\tau_u={}$".format(xy_delay))
fig.add_subplot(ax)
plt.show()
Upvotes: 2
Views: 2498
Reputation: 31
Just stumbled upon this as I had to do something similar. I found an easy solution was to create another Subplot for the outer grids and simply shutting their axes off:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(12, 6))
outer = gridspec.GridSpec(1, 2, wspace=0.2, hspace=0.2)
for i, layer in enumerate(layer_list):
# create inner plots
inner = gridspec.GridSpecFromSubplotSpec(2, 2,
subplot_spec=outer[i], wspace=0.1, hspace=0.1)
# set outer titles
ax = plt.Subplot(fig, outer[i])
ax.set_title("Layer {}".format(layer))
ax.axis('off')
fig.add_subplot(ax)
for j, filter_pos in enumerate(filter_pos_list):
# create image plot
ax = plt.Subplot(fig, inner[j])
# load image
img = ...
ax.imshow(img)
# set inner title
ax.set_title("Filter {}".format(filter_pos))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
fig.show()
Upvotes: 3