[英]Create grouped/stacked bar plots from multiple categories containing several labels inside a pandas dataframe
[英]How to create grouped bar plots in a single figure from a wide dataframe
我有以下 df:
test_df = pd.DataFrame({'name': ['a', 'b', 'c'], 'res1': [1,2,3], 'res2': [4,5,6]})
我想繪制(理想情況下,在一個圖表中)數據,因此我可以分別比較每行(每個名稱)的 res1 和 res2 。
我試圖實現類似的東西,但我想有一個更簡單、更優雅的解決方案,它也可以讓我將所有內容都放在一個圖表中,名稱為 x 軸上的一個組。
plt.subplot(1, 3, i+1)
sns.barplot(x=test_df.iloc[i,1:].index.tolist(), y=test_df.iloc[i,1:].values.tolist())
plt.title(test_df.iloc[i,0])
數據可以更容易地格式化,但可以通過將數據格式轉換為垂直格式並指定條形圖來將其表示為單個圖形。
import pandas as pd
import seaborn as sns
test_df = pd.DataFrame({'name': ['a', 'b', 'c'], 'res1': [1,2,3], 'res2': [4,5,6]})
df = test_df.set_index('name').unstack().to_frame(name='values')
df.reset_index(inplace=True)
df.rename(columns={'level_0':'categ'}, inplace=True)
sns.barplot(x='name', y='values', hue='categ', data=df)
類別 | 名稱 | 價值觀 | |
---|---|---|---|
0 | 資源 1 | 一種 | 1 |
1 | 資源 1 | 乙 | 2 |
2 | 資源 1 | C | 3 |
3 | 資源2 | 一種 | 4 |
4 | 資源2 | 乙 | 5 |
5 | 資源2 | C | 6 |
seaborn.barplot
或僅使用pandas.DataFrame.plot
來pandas.DataFrame.plot
,這避免了額外的導入。.bar_label
注釋,可用於matplotlib 3.4.2
。matplotlib
添加注釋。pandas 1.3.0
、 matplotlib 3.4.2
和seaborn 0.11.1
pandas.DataFrame.plot
name
作為索引值,或res1
和res2
作為索引。import pandas as pd
test_df = pd.DataFrame({'name': ['a', 'b', 'c'], 'res1': [1,2,3], 'res2': [4,5,6]})
# display(test_df)
name res1 res2
0 a 1 4
1 b 2 5
2 c 3 6
# set name as the index
test_df.set_index('name', inplace=True)
# display(test_df)
res1 res2
name
a 1 4
b 2 5
c 3 6
# plot and annotate
p1 = test_df.plot(kind='bar', rot=0)
for p in p1.containers:
p1.bar_label(p, fmt='%.1f', label_type='edge')
import pandas as pd
test_df = pd.DataFrame({'name': ['a', 'b', 'c'], 'res1': [1,2,3], 'res2': [4,5,6]})
# set name as the index and then Transpose the dataframe
test_df = test_df.set_index('name').T
# display(test_df)
name a b c
res1 1 2 3
res2 4 5 6
# plot and annotate
p1 = test_df.plot(kind='bar', rot=0)
for p in p1.containers:
p1.bar_label(p, fmt='%.1f', label_type='edge')
seaborn.barplot
pandas.DataFrame.melt
,然后使用hue
參數。import pandas as pd
import seaborn as sns
test_df = pd.DataFrame({'name': ['a', 'b', 'c'], 'res1': [1,2,3], 'res2': [4,5,6]})
# melt the dataframe into a long form
test_df = test_df.melt(id_vars='name')
# display(test_df.head())
name variable value
0 a res1 1
1 b res1 2
2 c res1 3
3 a res2 4
4 b res2 5
# plot the barplot using hue; switch the columns assigned to x and hue if you want a, b, and c on the x-axis.
p1 = sns.barplot(data=test_df, x='variable', y='value', hue='name')
# add annotations
for p in p1.containers:
p1.bar_label(p, fmt='%.1f', label_type='edge')
x='variable', hue='name'
x='name', hue='variable'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.