使用布局 - python的情节问题

时间:2016-11-22 14:22:56

标签: python pandas layout plot

我有2个名为headlamp_waterheadlamp_crack的子数据集: 对于这两个子数据集中的每一个,我想绘制2个图(1个hbar和其他箱图),最后将是4个图。

我使用以下代码:

def print_top_dealer(data, top, typegraph):
    if typegraph == "hbar":
        ax = data.Dealer.value_counts().iloc[:top].plot(kind="barh")
        ax.invert_yaxis()
    else:    
        ax = plt.boxplot(data['Use Period'], vert=False)

plt.close('all')    
ax1 = print_top_dealer(headlamp_water, 15, "hbar")
ax2 = print_top_dealer(headlamp_water, 15, "boxplot")
ax3 = print_top_dealer(headlamp_crack, 15, "hbar")
ax4 = print_top_dealer(headlamp_crack, 15, "boxplot")
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
plt.tight_layout()

enter image description here

并且,我将所有数据绘制到相同的图表中(最后一个) 如何将这4个图形绘制成(2x2)布局?

提前致谢

1 个答案:

答案 0 :(得分:1)

在调用plt.subplots时创建轴,需要使用它们。

这应该有用(我没有数据确认):

def print_top_dealer(data, top, ax, typegraph):
    if typegraph == "hbar":
        data.Dealer.value_counts().iloc[:top].plot(kind="barh", ax=ax)
        ax.invert_yaxis()
    else:    
        ax.boxplot(data['Use Period'], vert=False)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

print_top_dealer(data=headlamp_water, top=15, ax=ax1, typegraph="hbar")
print_top_dealer(data=headlamp_water, top=15, ax=ax2, typegraph="boxplot")
print_top_dealer(data=headlamp_crack, top=15, ax=ax3, typegraph="hbar")
print_top_dealer(data=headlamp_crack, top=15, ax=ax4, typegraph="boxplot")

plt.tight_layout()

由于您没有提供数据,因此这里有一些虚拟数据:

headlamp_water = pd.DataFrame(np.random.choice(['A1','A2','A3'], size=10), columns=['Dealer'])

headlamp_crack = pd.DataFrame(np.random.choice(['B1','B2','B3'], size=10), columns=['Dealer'])

headlamp_water['Use Period'] = np.random.rand(10)
headlamp_crack['Use Period'] = np.random.rand(10)

这是他们的样子:

print(headlamp_water)

  Dealer  Use Period
0     A3    0.058678
1     A3    0.734517
2     A1    0.371943
3     A2    0.290254
4     A3    0.869392
5     A3    0.082629
6     A3    0.069261
7     A1    0.089310
8     A3    0.633946
9     A2    0.176956

现在让我们试试图表:

def print_top_dealer(data, top, ax, typegraph):
    if typegraph == "hbar":
        data.Dealer.value_counts().iloc[:top].plot(kind="barh", ax=ax)
        ax.invert_yaxis()
    else:    
        ax.boxplot(data['Use Period'], vert=False,)

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

print_top_dealer(data=headlamp_water, top=15, ax=ax1, typegraph="hbar")
print_top_dealer(data=headlamp_water, top=15, ax=ax2, typegraph="boxplot")
print_top_dealer(data=headlamp_crack, top=15, ax=ax3, typegraph="hbar")
print_top_dealer(data=headlamp_crack, top=15, ax=ax4, typegraph="boxplot")

plt.tight_layout()

SUbplots