如何在嵌套的GridSpec中使用辅助y轴?

时间:2017-03-27 17:15:42

标签: python matplotlib

我想获得这个数字: enter image description here 但是每个图中都有两个图,如下所示: enter image description here 以下是我用于第一个图的代码示例

measures = ['ACE', 'SCE', 'LZs', 'LZc']
conditions = ['dark','light','flick3','flick10','switch']
    outer_grid = gridspec.GridSpec(2,2)
for measure in measures:
    inner_grid = gridspec.GridSpecFromSubplotSpec(5, 1, subplot_spec=outer_grid[measures.index(measure)])
    ax={}
    for cond in conditions:
        c=conditions.index(cond)
        ax[c] = plt.Subplot(fig, inner_grid[c])
        if c != 0:
            ax[c].get_shared_y_axes().join(ax[0], ax[c])
        ax[c].plot()
        ax[c+n]=ax[c].twinx()
        ax[c+n].scatter()
        ax[c+n].set_ylim(0,5)
        fig.add_subplot(ax[c],ax[c+n])

对于第二个图,它没有第一个循环和GridSpec基本相同,使用ax[c]=plt.subplot('51{c}')而不是ax[c]=plt.Subplot(fig, inner_grid[c])

正如您所看到的,当使用GridSpec时,我仍然具有辅助y轴,但没有关联的散点图。

我想简短的问题是如何正确撰写fig.add_subplot(ax[c],ax[c+n])

(两行fig.add_subplot(ax[c]) fig.add_subplot(ax[c+n])无效。)

1 个答案:

答案 0 :(得分:2)

从您的问题中不清楚您在每个子图中确切绘制了哪些数据,以及您创建子图的方式似乎有点复杂,这可能就是您遇到问题的原因。我将如何做到这一点:

import matplotlib.gridspec as gs
measures = ['ACE', 'SCE', 'LZs', 'LZc']
conditions = ['dark','light','flick3','flick10','switch']
colors = ['g','c','b','r','grey']
Npoints = 10
data = [np.random.random((Npoints,len(measures))) for i in range(len(conditions))]
gs00 = gs.GridSpec(len(conditions), 1)

fig = plt.figure(figsize=(5,5))

for i,condition in enumerate(conditions):
    ax1 = fig.add_subplot(gs00[i])
    ax2 = ax1.twinx()
    ax1.plot(range(Npoints), data[i][:,0], 'o-', color=colors[i], label=measures[0])
    ax2.plot(range(Npoints), data[i][:,1], 'o-.', color=colors[i], label=measures[1])

    ax1.set_ylim((-0.1,1.1))
    ax2.set_ylim(ax1.get_ylim())

    ax1.set_title(condition)

enter image description here

编辑重复4次同样的事情,逻辑是完全一样的,你只需要玩gridspec。但唯一重要的是ax1 = fig.add_subplot(gs01[j])后跟ax2 = ax1.twinx()的行,它将在第一个

之上创建第二个轴
import matplotlib.gridspec as gs
measures = ['ACE', 'SCE', 'LZs', 'LZc']
conditions = ['dark','light','flick3','flick10','switch']
colors = ['g','c','b','r','grey']
Npoints = 10
data = [np.random.random((Npoints,len(measures))) for i in range(len(conditions))]
gs00 = gs.GridSpec(2,2)

plt.style.use('seaborn-paper')
fig = plt.figure(figsize=(10,10))

grid_x, grid_y = np.unravel_index(range(len(measures)),(2,2))

for i,measure in enumerate(measures):
    gs01 = gs.GridSpecFromSubplotSpec(len(conditions), 1, subplot_spec=gs00[grid_x[i],grid_y[i]])
    for j,condition in enumerate(conditions):
        ax1 = fig.add_subplot(gs01[j])
        ax2 = ax1.twinx()
        ax1.plot(range(Npoints), data[j][:,0], 'o-', color=colors[j], label=measures[0])
        ax2.plot(range(Npoints), data[j][:,1], 'o-.', color=colors[j], label=measures[1])

        ax1.set_ylim((-0.1,1.1))
        ax2.set_ylim(ax1.get_ylim())

        if j==0:
            ax1.set_title(measure)

enter image description here