Matplotlib:在子图网格中重新定位子图 [英] Matplotlib: Repositioning a subplot in a grid of subplots

查看:66
本文介绍了Matplotlib:在子图网格中重新定位子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用7个子图进行绘制.目前,我正在绘制两列,其中一列包含四幅图,另一列包含三幅图,例如:

I am trying to make a plot with 7 subplots. At the moment I am plotting two columns, one with four plots and the other with three, i.e. like this:

我正在按照以下方式构建该图:

I am constructing this plot in the folowing way:

    #! /usr/bin/env python
    import numpy as plotting
    import matplotlib
    from pylab import *
    x = np.random.rand(20)
    y = np.random.rand(20)
    fig = figure(figsize=(6.5,12))
    subplots_adjust(wspace=0.2,hspace=0.2)
    iplot = 420
    for i in range(7):
       iplot += 1
       ax = fig.add_subplot(iplot)
       ax.plot(x,y,'ko')
       ax.set_xlabel("x")
       ax.set_ylabel("y")
    savefig("subplots_example.png",bbox_inches='tight')

但是,对于发布,我认为这看起来有些丑陋-我想做的是将最后一个子图移到两列之间的中间.那么,调整最后一个子图的位置使其居中的最佳方法是什么?IE.在3X2网格中具有前6个子图,而最后一个子图在两列之间居中.如果可能的话,我希望能够保留 for 循环,以便我可以简单地使用:

However, for publication I think this looks a bit ugly -- what I would like to do is move the last subplot into the centre between the two columns. So, what is the best way to adjust the position of the last subplot so that it is centred? I.e. to have the first 6 subplots in a 3X2 grid and the last subplot underneath centred between the two columns. If possible, I'd like to be able to keep the for loop so that I can simply use:

    if i == 6:
       # do something to reposition/centre this plot     

谢谢

亚历克斯

推荐答案

如果要保留for循环,可以使用 subplot2grid 布置图,该图允许 colspan 参数:

If you want to keep the for loop, you can arrange your plots with subplot2grid, which allows for a colspan parameter:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(20)
y = np.random.rand(20)
fig = plt.figure(figsize=(6.5,12))
plt.subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
    iplot += 1
    if i == 6:
        ax = plt.subplot2grid((4,8), (i//2, 2), colspan=4)
    else:
        # You can be fancy and use subplot2grid for each plot, which doesn't
        # require keeping the iplot variable:
        # ax = plt.subplot2grid((4,2), (i//2,i%2))

        # Or you can keep using add_subplot, which may be simpler:
        ax = fig.add_subplot(iplot)
    ax.plot(x,y,'ko')
    ax.set_xlabel("x")
    ax.set_ylabel("y")
plt.savefig("subplots_example.png",bbox_inches='tight')

这篇关于Matplotlib:在子图网格中重新定位子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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