我有一个数据框,例如下面,其中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循环。谢谢。
发布于 2020-02-21 18:38:21
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')

请注意,仅使用pandas也可以获得相同的结果,但首先需要对数据进行整形
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']])

发布于 2020-02-21 19:13:26
你可以这样做:
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()

https://stackoverflow.com/questions/60336648
复制相似问题