Matplotlib-向子图中添加子图? [英] Matplotlib - adding subplots to a subplot?

查看:481
本文介绍了Matplotlib-向子图中添加子图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个由2x2网格组成的图形,其中在每个象限中有2个垂直堆叠的子图(即2x1网格).不过,我似乎无法弄清楚该如何实现.

I'm trying to create a figure that consists of a 2x2 grid, where in each quadrant there are 2 vertically stacked subplots (i.e. a 2x1 grid). I can't seem to figure out how to achieve this, though.

我最近得到的是使用gridspec和一些难看的代码(请参见下文),但是由于gridspec.update(hspace=X)更改了所有子图的间距,所以我仍然不在我想要的位置.

The closest I've gotten is using gridspec and some ugly code (see below), but because gridspec.update(hspace=X) changes the spacing for all of the subplots I'm still not where I'd like to be.

理想情况下,我想要的是,以下面的图片为例,减小每个象限内子图之间的间距,同时增加顶部和底部象限之间的垂直间距(即1-3和2-4之间) .

Ideally what I want is to, using the picture below as an example, decrease the spacing between the subplots within each quadrant, while increasing the vertical spacing between the top and bottom quadrants (i.e. between 1-3 and 2-4).

有没有办法做到这一点(使用或不使用gridspec)?我最初的设想是生成每个子子图网格(即每个2x1网格)并将其插入到更大的2x2子图网格中,但是我还没有弄清楚如何向子图添加子图,即使有离开.

Is there a way to do this (with or without using gridspec)? What I originally envisioned is generating each of the sub-subplot grids (i.e. each 2x1 grid) and inserting them into the larger 2x2 grid of subplots, but I haven't figured out how to add a subplot to a subplot, if there is even a way.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(4,2)
gs.update(hspace=0.4)
for i in range(2):
    for j in range(4):
        ax = plt.subplot(gs[j,i])
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        plt.tick_params(which='both', top='off', right='off')
        if j % 2 == 0:
            ax.set_title(str(i+j+1))
            ax.plot([1,2,3], [1,2,3])
            ax.spines['bottom'].set_visible(False)
            ax.get_xaxis().set_visible(False)   
        else:
            ax.plot([1,2,3], [3,2,1])

推荐答案

您可以使用SubplotSpec嵌套您的GridSpec .外部网格将为2 x 2,内部网格将为2 x1.以下代码应为您提供基本概念.

You can nest your GridSpec using SubplotSpec. The outer grid will be a 2 x 2 and the inner grids will be 2 x 1. The following code should give you the basic idea.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2)

for i in range(4):
    inner = gridspec.GridSpecFromSubplotSpec(2, 1,
                    subplot_spec=outer[i], wspace=0.1, hspace=0.1)

    for j in range(2):
        ax = plt.Subplot(fig, inner[j])
        t = ax.text(0.5,0.5, 'outer=%d, inner=%d' % (i,j))
        t.set_ha('center')
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)

fig.show()

这篇关于Matplotlib-向子图中添加子图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆