【发布时间】:2019-10-14 22:05:31
【问题描述】:
我在 pandas 中有以下数据框:
它按数据集中参与者的年龄范围进行分组/索引。对于数据框中的每个年龄范围,我想生成一个条形图,其条形显示该特定年龄范围的离婚率、结婚率等。如何使用 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
【问题讨论】:
-
很有可能。有很多方法可以做到这一点。您需要更具体地了解您想要什么样的条形图(例如,刻面、堆叠......)。您还应该以可复制的格式包含您的数据框
-
您好,感谢您的反馈。我用可复制粘贴格式的数据框代码更新了帖子。我想要它的刻面。
-
只需
df.plot.bar()?
标签: python python-3.x pandas matplotlib seaborn