Matplotlib subplot2grid在设置gridspec_kw width_ratios时删除子图

时间:2018-06-13 15:36:58

标签: matplotlib

我正在尝试制作一个子图的网格,其中一个轴跨越两个网格位置。我可以使用plt.subplotsgridspec_kwplt.subplot2grid

轻松实现这一目标
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,3,sharex=True, sharey=True, gridspec_kw={'width_ratios':[1,1,0.8]})
axi = plt.subplot2grid((2,3),(0,2),rowspan=2)
plt.show()

Basic setup

但是,我希望右侧的生长轴更窄。当我将width_ratios更改为[1,1,0.5]时,我明白这一点:

Gridspec error

其他轴发生了什么变化?基于this answer,我可以直接使用GridSpec来实现我想要的,而不是使用便利包装器:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(nrows=2, ncols=3, width_ratios=[1,1,0.5])
ax0 = plt.subplot(gs[0,0])
ax1 = plt.subplot(gs[0,1],sharey=ax0)
ax2 = plt.subplot(gs[1,0],sharex=ax0)
ax3 = plt.subplot(gs[1,1],sharex=ax1,sharey=ax2)
ax4 = plt.subplot(gs[:,2])
[plt.setp(z.get_yticklabels(),visible=False) for z in [ax1,ax3]]
[plt.setp(z.get_xticklabels(),visible=False) for z in [ax0,ax1]]
plt.show()

Using GridSpec

虽然这有效,但必须手动设置所有内容,特别是当我只用两行代码就可以如此接近时,这是很繁琐的。有没有人想过如何使用subplots / subplot2grid来完成这项工作,还是我坚持不懈地做这件事?这值得关于GitHub的问题报告吗?

2 个答案:

答案 0 :(得分:1)

要报告的问题可能与您想象的不同。我刚刚创建了this one

GridSpec相当的工作代码(这肯定是一个有效且好的解决方案),可以使用fig.add_subplot代替plt.subplot2grid,并从中移除两个不需要的轴初始网格。

import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,3,sharex=True, sharey=True, gridspec_kw={'width_ratios':[1,1,0.8]})
axi = fig.add_subplot(133)

for a in ax[:,2]:
    a.axis("off")
plt.show()

答案 1 :(得分:1)

感谢the answer of @ImportanceOfBeingErnest,我能够解决这个问题。在

fig, ax = plt.subplots(2,3,sharex=True, sharey=True, gridspec_kw={'width_ratios':[1,1,0.5]})

根据需要设置轴的宽度。但是,虽然我想要的行为

axi = plt.subplot2grid((2,3),(0,2),rowspan=2)

是跨越现有子图的整个第三列,实际上它会创建宽度比为2x3虚拟[1,1,1]网格并写入跨越此新网格右列的轴。由于这个新的右列是图形宽度的1/3,它与原始子图的中心列的一部分重叠,导致它们消失。

为了将此代码保留为两行代码,解决方案是更改subplot2grid调用以模拟所需的宽度比:

axi = plt.subplot2grid((2,5),(0,4),rowspan=2)

我通过转换原始width_ratios向量2*[1,1,0.5] = [2,2,1]sum([2,2,1]) = 5来获得网格的5列。基本上,由于subplot2grid不知道width_ratios中指定的subplots,因此您必须强制它适应新的网格计算。

enter image description here

相关问题