我目前正在尝试使用 GridSpec 在 Matplotlib(Python 3.6、Matplotlib 2.0.0)中绘制许多子图。这是最小的工作示例:
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)
这是没有任何修改的结果:
当然,子图之间的间距并不令人满意,所以我做了我通常做的事情并使用了tight_layout()
。但如下图所示,tight_layout()
挤压了图的宽度,令人无法接受:
我认为我应该使用subplots_adjust()
手动调整子图,而不是使用tight_layout()
。下图是带有 subplots_adjust(hspace=1.0, wspace=1.0)
的图。
结果几乎是正确的,如果稍微调整一下子图之间的空间就会很完美。然而,子图看起来太小,无法充分传达信息。
有没有更好的方法可以在子图之间获得适当的间距,同时仍然保持纵横比和足够大的子图尺寸?我能想到的唯一可能的解决方案是使用 subplots_adjust()
和更大的 figsize
,但这会导致图形边缘和图形边缘之间的空间非常大。次要情节。
任何解决方案都值得赞赏。
最佳答案
由于所有轴都具有相同的 x
和 y
范围,我会选择仅在外部轴
上显示刻度标签。对于大小相等的子图网格,可以使用 plt.subplots()
的 sharex
和 sharey
关键字轻松实现自动化。当然,如果您设置了 9x9 子图的网格,则会提供比您想要的更多的图,但您可以使冗余图不可见(例如使用 Axes.set_visible 或完全删除它们)。在下面的示例中,我选择后者。
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()
结果如下所示:
当然可以使用 subplots_adjust()
之类的方法进一步调整。希望这会有所帮助。
关于python - Matplotlib 子图太窄且布局紧凑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201514/