我在熊猫中有以下数据框:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9vN1I0WVJPLnBuZyJ9” alt =“ Dataframe”>
它是根据数据集中参与者的年龄范围进行分组/索引的。对于数据框中的每个年龄段,我想生成一个条形图,其条形图显示该特定年龄段的离婚率,结婚率等。如何使用matplotlib或seaborn做到这一点?预先感谢您提供的任何帮助。
用于生成数据框的代码:
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
plt.style.use('ggplot')
df = pd.DataFrame({
'age_range': [(18, 28), (28, 38), (38, 48), (48, 58), (58, 68), (68, 78), (78, 88)],
'divorced': [0.015837, 0.068826, 0.138132, 0.185022, 0.180258, 0.179211, 0.099502],
'living with partner': [0.21040724, 0.14979757, 0.07392996, 0.06828194, 0.04506438, 0.01075269, 0.00995025],
'married': [0.24208145, 0.51619433, 0.57198444, 0.54625551, 0.50429185, 0.37992832, 0.28855721],
'never_married': [0.50904977, 0.23279352, 0.14202335, 0.08370044, 0.09012876,0.05734767, 0.05472637],
'refused': [np.nan, np.nan, np.nan, np.nan, 0.00214592, np.nan, np.nan],
'widowed': [np.nan, 0.00202429, 0.0155642 , 0.05506608, 0.12875536, 0.33691756, 0.53731343]
})
df.set_index('age_range', inplace=True)
df
如果您不想要堆叠蝙蝠并且确实希望它带有色调,那么使用seaborn可以很快:
g = (
df.stack()
.to_frame('Count')
.rename_axis(index=['Age Range', 'Status'])
.reset_index()
.pipe((sns.factorplot, 'data'),
x='Age Range', y='Count',
hue='Status', kind='bar',
size=3.5, aspect=1.86)
)
或者您可以按列查看:
g = (
df.stack()
.to_frame('Count')
.rename_axis(index=['Age Range', 'Status'])
.reset_index()
.pipe((sns.factorplot, 'data'),
x='Age Range', y='Count',
col='Status', kind='bar',
size=3.5, aspect=1.86, col_wrap=2)
)