使用matplotlib重塑图中的轴

时间:2018-05-04 18:17:13

标签: python matplotlib figure subplot

我正在使用matplotlib生成数字的库中的方法。

我收到了一系列轴:

[<matplotlib.axes._axes.Axes at 0x117a32a90>,
 <matplotlib.axes._axes.Axes at 0x117bb1d68>,
 <matplotlib.axes._axes.Axes at 0x10bae8390>,
 <matplotlib.axes._axes.Axes at 0x10bb0add8>,
 <matplotlib.axes._axes.Axes at 0x10c153898>,
 <matplotlib.axes._axes.Axes at 0x1159412e8>,
 <matplotlib.axes._axes.Axes at 0x115964d30>]

在原始图中,所有轴都在同一行(参见第一张图,并想象右侧有另外两个轴)。我想重新塑造这个图形,以便创建一个轴网格(见第二张图)。

a

b

有可能吗?

更新 - 我尝试了什么

关注this answer,我尝试使用GridSpec:

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

fig = plt.figure()

axs = #get list of axes

gs = gridspec.GridSpec(3,3)
for i in range(3):
    for j in range(3):
        k = i+j*3
        if k < len(axs):
            axs[k].set_position(gs[k].get_position(fig))    
            fig.add_subplot(gs[k])

但它不起作用,我还没有完全掌握GridSpec。该图显示了正确的子图数,但未添加轴。

2 个答案:

答案 0 :(得分:1)

我想你差不多了。不知道你的绘图功能是什么,我只是做了一个虚拟的插图。

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


def dummy_plots():
    """
    Return a 1d array of dummy plots.
    """
    _, ax_arr = plt.subplots(1, 9)

    for ax in ax_arr.flat:
        ax.plot([0, 1], [0, 1])

    return ax_arr


axs = dummy_plots()
fig = plt.gcf()

gs = gridspec.GridSpec(3,3)
for i in range(3):
    for j in range(3):
        k = i+j*3
        if k < len(axs):
            axs[k].set_position(gs[k].get_position(fig))

plt.show()

enter image description here

答案 1 :(得分:0)

在许多情况下,我发现更容易做到的是:

import numpy as np
import matplotlib.pyplot as plt

f, ax = plt.subplots(2, 2)
# make 1d for easier access
ax = np.ravel(ax)
for i in range(4):
    ax[i].plot([0,1], [0, 1], c=f"C{i}")
# reshape to initial dimensions
ax = np.reshape(ax, (2, 2))

enter image description here

相关问题