首页 > 解决方案 > 在 gridspec 项内具有共享轴的多个子图

问题描述

我想要一个有 2 列和 1 行的网格。第一列将包含不同国家/地区的地图,第二列应为垂直堆叠的地图中的每个国家/地区提供一个图。

这些图应该共享 x 轴,我想plt.subplotssharex=True.

但是,在我看到的示例中(例如这个),他们首先创建网格,然后一次添加一个子图。这样我猜我就不能使用共享轴了。有没有办法结合网格来做到这一点?

期望的输出:

网格中的子图

我尝试的是为网格定义与在我的图右侧分别绘制的国家数量一样多的行,而没有找到使用sharex=True.

这是一个简化的示例(从https://towardsdatascience.com/plot-organization-in-matplotlib-your-one-stop-guide-if-you-are-reading-this-it-is-probably-f79c2dcbc801修改) :

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))

fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)

ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[1, 1])
plt.show()

标签: pythonmatplotlibgridsubplot

解决方案


好的,抱歉,我在这里找到了解决方案。

诀窍是设置sharex等于已创建的 x 轴之一,然后显式隐藏除下图以外的所有 x 刻度(在我的情况下)。

这是修改后的代码:

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))

fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)

ax1 = fig.add_subplot(gs[1, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
plt.show()

推荐阅读