Matplotlib:当左边有3个图2,右边有1个时,共享轴

2024-05-13 04:13:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下图表: enter image description here

但是,我希望图221和223共享同一个x轴。我有以下代码:

self.fig_part_1 = plt.figure()
self.plots_part_1 = [
  plt.subplot(221),
  plt.subplot(223),
  plt.subplot(122),
]

我怎么才能做到呢?最后,我不想显示221号地块中x轴的编号。在


Tags: 代码self图表figplt编号figurepart
2条回答

(这主要是对@H.Rev.的评论。但我把它作为一个“答案”发布,以获得更好的代码格式)

我认为最好是手动添加子批次,因为当您现在实现它时,它将提供两个轴,而您只需丢弃它们。它们甚至可能会出现重叠轴记号的问题,并且通常会造成很多混乱。我认为最好先创建图形,然后逐个添加轴。这种方法还解决了这个问题,因为您可以直接访问例如fig_N,所以必须用plt.figure(self.f.number)来“更新”当前图形

import matplotlib.pyplot as plt

fig1 = plt.figure()
# fig2 = plt.figure()  # more figures are easily accessible
# fig3 = plt.figure()  # more figures are easily accessible

ax11 = fig1.add_subplot(221)  # add subplot into first position in a 2x2 grid (upper left)
ax12 = fig1.add_subplot(223, sharex=ax11)  # add to third position in 2x2 grid (lower left) and sharex with ax11
ax13 = fig1.add_subplot(122)  # add subplot to cover both upper and lower right, in a 2x2 grid. This is the same as the rightmost panel in a 1x2 grid.
# ax21 = fig2.add_subplot(211)  # add axes to the extra figures
# ax21 = fig2.add_subplot(212)  # add axes to the extra figures
# ax31 = fig3.add_subplot(111)  # add axes to the extra figures
plt.show()

只需使用plt.subplots(不同于plt.subplot)定义所有轴,并使用选项sharex=True

f, axes = plt.subplots(2,2, sharex=True)
plt.subplot(122)
plt.show()

请注意,第二个具有较大子时隙数组的调用覆盖了前一个调用。

Example(由于信誉问题无法显示图像…)

相关问题 更多 >