问题
I am currently trying to plot many subplots in Matplotlib (Python 3.6, Matplotlib 2.0.0) using GridSpec. Here is the minimal working example:
import matplotlib.pyplot as plt
from matplotlib.gridspec import *
# Color vector for scatter plot points
preds = np.random.randint(2, size=100000)
# Setup the scatter plots
fig = plt.figure(figsize=(8,8))
grid = GridSpec(9, 9)
# Create the scatter plots
for ii in np.arange(0, 9):
for jj in np.arange(0, 9):
if (ii > jj):
ax = fig.add_subplot(grid[ii, jj])
x = np.random.rand(100000)*2000
y = np.random.rand(100000)*2000
ax.scatter(x, y, c=preds)
This is the result without any modifications:
Of course the spacing between subplots is unsatisfactory so I did what I usually do and used tight_layout()
. But as can be seen in the figure below, tight_layout()
squeezes the width of the plots unacceptably:
Instead of using tight_layout()
, I figured I should just adjust the subplots manually using subplots_adjust()
. Below is the figure with subplots_adjust(hspace=1.0, wspace=1.0)
.
The result is almost correct, and with a little more tweaking the space between subplots would be perfect. However the subplots appear too small to adequately convey information.
Is there a better way to get proper spacing between subplots while still maintaining aspect ratio and a large enough subplot size? The only possible solution I could come up with was to use subplots_adjust()
with a larger figsize
, but this results in a very large space between the edges of the figure and the subplots.
Any solutions are appreciated.
回答1:
As all your axes have the same x
and y
ranges, I would choose to show the tick labels only on the outer Axes
. For a grid of equally-sized subplots, this is easily automated with the sharex
and sharey
keywords of plt.subplots()
. Of course, if you set up a grid of 9x9 subplots, that gives you more plots than you want, but you can either make the redundant plots invisible (for instance with Axes.set_visible
or remove them entirely. In the example below I go with the latter.
from matplotlib import pyplot as plt
import numpy as np
fig, axes = plt.subplots(
nrows=9, ncols=9, sharex=True, sharey=True, figsize = (8,8)
)
# Color vector for scatter plot points
preds = np.random.randint(2, size=1000)
# Create the scatter plots
for ii in np.arange(0, 9):
for jj in np.arange(0, 9):
if (ii > jj):
ax = axes[ii,jj]
x = np.random.rand(1000)*100
y = np.random.rand(1000)*2000
ax.scatter(x, y, c=preds)
else:
axes[ii,jj].remove() ##remove Axes from fig
axes[ii,jj] = None ##make sure that there are no 'dangling' references.
plt.show()
The resulting figure looks like this:
This can be of course adjusted further with something like subplots_adjust()
. Hope this helps.
来源:https://stackoverflow.com/questions/51201514/matplotlib-subplots-are-too-narrow-with-tight-layout