例如,我有一个数据框,其中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
我希望能够有一个2x2子图,该子图由基于4行的条形图组成。 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循环。谢谢。
答案 0 :(得分:1)
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')
请注意,仅使用熊猫即可获得相同的结果,但首先需要重塑数据
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']])
答案 1 :(得分:0)
您可以通过以下方式进行:
df = df.set_index('Material')
fig = plt.figure(figsize=(10,8))
for i, (name, row) in enumerate(df.iterrows()):
ax = plt.subplot(2,2, i+1)
ax.set_title(row.name)
ax.get_xaxis().set_visible(False)
df.iloc[i].plot.bar(color=['C0', 'C1'])
fig.legend(ax.bar([0,0],[0,0], color=['C0','C1']),['A','B'], loc=5)
plt.show()