pandas 海运多重条形图

yfjy0ee7  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(99)

我有一个Pandas的框架,看起来像这样:

class       men       woman   children
0   first   0.91468    0.667971   0.660562
1   second  0.30012    0.329380   0.882608
2   third   0.11899    0.189747   0.121259

字符串
我如何使用seaborn创建一个像这样的图?我必须以某种方式重新排列我的数据吗?


的数据
(来源:mwaskom at stanford.edu

mjqavswn

mjqavswn1#

python 3.12.0pandas 2.1.1matplotlib 3.8.0seaborn 0.13.0中测试

使用pandas.DataFrame.meltpandas.melt重塑DataFrame:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# convert the dataframe to a long format
dfm = pd.melt(df, id_vars="class", var_name="sex", value_name="survival rate")
dfm
Out: 
    class       sex  survival rate
0   first       men       0.914680
1  second       men       0.300120
2   third       men       0.118990
3   first     woman       0.667971
4  second     woman       0.329380
5   third     woman       0.189747
6   first  children       0.660562
7  second  children       0.882608
8   third  children       0.121259

字符串
通过创建具有分组条的单个面而不是具有单个条的多个面来合并图。
使用figure-level方法sns.catplot绘图

g = sns.catplot(x='class', y='survival rate', hue='sex', data=dfm, kind='bar', height=5, aspect=1)


使用axes-level方法sns.barplot绘图

# the following code matches the plot produced by catplot
plt.figure(figsize=(5, 5))
ax = sns.barplot(x='class', y='survival rate', hue='sex', data=dfm)
ax.spines[['top', 'right']].set_visible(False)
sns.move_legend(ax, bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)


的数据

弃用

factorplot(v0.8.1或更早版本):

sns.factorplot(x='class', y='survival rate', hue='sex', data=df, kind='bar')

wgx48brx

wgx48brx2#

为了在OP中生成绘图,我使用了以下代码,在将框架从宽格式转换为长格式之后。

python 3.12.0pandas 2.1.1matplotlib 3.8.0seaborn 0.13.0中测试

数据类型:

d = {'class': ['first', 'second', 'third', 'first', 'second', 'third', 'first', 'second', 'third'], 'sex': ['men', 'men', 'men', 'woman', 'woman', 'woman', 'children', 'children', 'children'], 'survival_rate':[0.914680, 0.300120, 0.118990, 0.667971, 0.329380, 0.189747, 0.660562, 0.882608, 0.121259]} 

df = pd.DataFrame(data=d)

字符串


的数据

g = sns.catplot(kind='bar', data=df, x='sex', y='survival_rate', col='class')


弃用

sns.factorplot("sex", "survival_rate", col="class", data=df, kind="bar")


相关问题