[英]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.