gpt4 book ai didi

python - 使用布局的绘图问题 - python

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:15 24 4
gpt4 key购买 nike

我有 2 个子数据集,名为 headlamp_waterheadlamp_crack:对于这 2 个子数据集中的每一个,我想绘制 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) 布局中?

提前致谢

最佳答案

调用 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

关于python - 使用布局的绘图问题 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40744342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com