Reputation: 85
I have a dataframe for example the following, where Material, A and B are all column headings:
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
I want to be able to have a 2x2 subplots consisting of bar graphs based on the 4 rows. The heading of each of the 4 subplots would be the material. Each subplot would have two bars for each value of A and B, each bar is in the subplot have a colour associated to A and B. Finally also would be nice to have a legend showing the colour and what it represents i.e. A and 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
I think a for loop would be the best way to do it, but simply cannot figure out the for loop. Thanks.
Upvotes: 3
Views: 2728
Reputation: 12417
You can do in this way:
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()
Upvotes: 0
Reputation: 40747
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')
Note that the same result can be achieved using pandas only, but first you need to reshape your data
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']])
Upvotes: 2