matplotlib subplot2grid无法正确显示

时间:2015-07-31 00:55:13

标签: python-2.7 matplotlib

我正在使用subplot2grid来显示图形。但是,并非所有子图都显示。显然它与if语句有关。 但是,在我的完整代码中,我需要那些if语句,因为根据某些条件,绘图具有不同的格式。我希望显示所有3个子图(每个i一个)。但是,第一个缺失了。如何正确显示?

以下是简化代码:

import matplotlib.pyplot as plt
fig=plt.figure()
for i in xrange(0,3):  
    if i==1:
        ax=plt.subplot2grid((3,1),(i,0))
        ax.plot([1,2],[1,2])
        fig.autofmt_xdate()
    else:
        ax=plt.subplot2grid((3,1),(i,0), rowspan=2)
        ax.plot([1,2],[1,2])
        fig.autofmt_xdate()
plt.show()

1 个答案:

答案 0 :(得分:1)

I would just use the gridspec module from matplotlib. Then you can set the width/height ratios directly.

Then you can do something like this:

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

def do_plot_1(ax):
    ax.plot([0.25, 0.5, 0.75], [0.25, 0.5, 0.75], 'k-')

def do_plot_2(ax):
    ax.plot([0.25, 0.5, 0.75], [0.25, 0.5, 0.75], 'g--')


fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=3, ncols=1, height_ratios=[2, 1, 2])

for n in range(3):
    ax = fig.add_subplot(gs[n])
    if n == 1:
        do_plot_1(ax)
    else:
        do_plot_2(ax)

fig.tight_layout()

enter image description here

To use plt.subplot2grid, you'd need to effectively do something like this:

fig = plt.figure(figsize=(6, 4))
ax1 = plt.subplot2grid((5,1), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((5,1), (2, 0), rowspan=1)
ax3 = plt.subplot2grid((5,1), (3, 0), rowspan=2)

Since you have two axes with a rowspan=2, your grid needs to be 2+1+2 = 5 blocks tall.

相关问题