gpt4 book ai didi

python - 为数据框中的每一行创建条形图的子图

转载 作者:行者123 更新时间:2023-12-05 05:05:46 26 4
gpt4 key购买 nike

我有一个数据框,例如以下内容,其中 Material、A 和 B 都是列标题:

    Material    A           B
0 Iron 20.30000 5.040409
1 Antimony 0.09200 0.019933
2 Chromium 1.70000 0.237762
3 Copper 8.10000 2.522951

我希望能够有一个由基于 4 行的条形图组成的 2x2 子图。 4 个子图中每个子图的标题都是素材。每个子图都会有两个条形图表示 A 和 B 的每个值,子图中的每个条形图都有一个与 A 和 B 相关联的颜色。最后还有一个图例显示颜色及其代表的内容,即 A 和 B。

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.style as style
sns.set_style("darkgrid")

fig, ax = plt.subplots(2,2)

#Enter for loop

我认为 for 循环是最好的方法,但就是想不出 for 循环。谢谢。

最佳答案

fig, axs = plt.subplots(2,2, constrained_layout=True)
for ax,(idx,row) in zip(axs.flat, df.iterrows()):
row[['A','B']].plot.bar(ax=ax, color=['C0','C1'])
ax.set_title(row['Material'])

proxy = ax.bar([0,0],[0,0], color=['C0','C1'])
fig.legend(proxy,['A','B'], bbox_to_anchor=(1,1), loc='upper right')

enter image description here

请注意,仅使用 pandas 即可获得相同的结果,但首先您需要 reshape 数据

df2 = df.set_index('Material').T

>>
Material Iron Antimony Chromium Copper
A 20.300000 0.092000 1.700000 8.100000
B 5.040409 0.019933 0.237762 2.522951

df2.plot(kind='bar', subplots=True, layout=(2,2), legend=False, color=[['C0','C1']])

enter image description here

关于python - 为数据框中的每一行创建条形图的子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60336648/

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