2017-05-18 113 views
1

我正在创建一个轴数组的PDF。有时页面未满,即并非所有轴都有数据。在这种情况下,我希望未使用的轴不显示在PDF上。但我希望布局与使用布局相同。我正在使用tight_layout()来获取非重叠的坐标轴和ylabels。在matplotlib中使用tight_layout()与不完整的轴数组:

下面的代码首先显示了使用坐标轴的情况,然后如果我删除未使用的坐标轴(tight_layout不能正常工作)会发生什么情况,如果我只是将它们设置为不可见,那么tight_layout( )不合格

AttributeError: 'NoneType' object has no attribute 'is_bbox'

错误。

import numpy as np 
import matplotlib.pyplot as plt 
def prep_figure(): 
    plt.close('all') 
    fig, axs = plt.subplots(4,3, figsize=(11,8.5)) 
    axs=np.concatenate(axs) 
    for ii in range(5): 
     axs[ii].plot([1,2,3],[-10,-1,-10]) 
     axs[ii].set_ylabel('ylabel') 
     axs[ii].set_xlabel('xlabel') 
    return fig,axs 

fig,axs=prep_figure() 
plt.tight_layout() 
plt.show() 
plt.savefig('tmp.pdf',) 

# Try deleting extra axes 
fig,axs=prep_figure() 
for ii in range(5,12): 
    fig.delaxes(axs[ii]) 
plt.tight_layout() 
plt.show() 
plt.savefig('tmpd.pdf',) 

# Try hiding extra axes 
fig,axs=prep_figure() 
for ii in range(5,12): 
    axs[ii].set_visible(False) 
plt.tight_layout() 
plt.show() 
plt.savefig('tmph.pdf',) 

我想要第一个版本的布局,但没有额外的轴可见。

回答

0

您可以独立于图形创建轴。我也推荐这种方法,因为你可以对轴进行更多的控制,例如你可以有不同形状的轴。

代码:

import numpy as np 
import matplotlib.pyplot as plt 

fig = plt.figure() 
for ii in range(5): 
    ax = fig.add_subplot(4,3,ii+1) 
    ax.scatter(np.random.random(5),np.random.random(5)) 
    ax.set_xlabel('xlabel') 
    ax.set_ylabel('ylabel') 
fig.tight_layout() 
fig.show() 

结果:enter image description here

0

,如果它在其自身的使用(不从所执行的第一种情况下的代码)删除轴的第二壳体工作正常,如果该图首先被保存,然后显示,

fig,axs=prep_figure() 
for ii in range(5,12): 
    fig.delaxes(axs[ii]) 
plt.tight_layout() 
plt.savefig('tmpd.pdf',) 
plt.show() 

如果再次,这个数字被保存在第三种情况下工作正常显示它和,而不是使其不可见之前,通过ax.axis("off")关闭轴。

fig,axs=prep_figure() 
for ii in range(5,12): 
    axs[ii].axis("off") 
plt.tight_layout() 
plt.savefig('tmph.pdf',) 
plt.show() 

创建的PDF是在两种情况下是相同的:

enter image description here