使用布局python的绘图问题

2024-06-17 11:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个子数据集叫做headlamp_waterheadlamp_crack: 对于这两个子数据集中的每一个子数据集,我想绘制2个图(1个hbar和其他boxplot),其中j最后是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)布局

提前谢谢


Tags: 数据datatop绘制pltaxprintcrack
1条回答
网友
1楼 · 发布于 2024-06-17 11:41:49

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

这应该有效(我没有你的数据来确认):

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

相关问题 更多 >