我写了一个(新手)python 函数(如下)来绘制一个按主要维度和可能的次要维度划分的条形图。例如,下图显示了每种性别中获得特定教育水平的人数百分比。
问题:如何在每个条形上叠加该子组的家庭规模中位数,例如在大学/女性条形上放置一个表示值“3”的点。我见过的例子都没有准确地将点覆盖在正确的栏上。
我对此非常陌生,所以非常感谢您的帮助!
df = pd.DataFrame({'Student' : ['Alice', 'Bob', 'Chris', 'Dave', 'Edna', 'Frank'],
'Education' : ['HS', 'HS', 'HS', 'College', 'College', 'HS' ],
'Household Size': [4, 4, 3, 3, 3, 6 ],
'Gender' : ['F', 'M', 'M', 'M', 'F', 'M' ]});
def MakePercentageFrequencyTable(dataFrame, primaryDimension, secondaryDimension=None, extraAggregatedField=None):
lod = dataFrame.groupby([secondaryDimension]) if secondaryDimension is not None else dataFrame
primaryDimensionPercent = lod[primaryDimension].value_counts(normalize=True) \
.rename('percentage') \
.mul(100) \
.reset_index(drop=False);
if secondaryDimension is not None:
primaryDimensionPercent = primaryDimensionPercent.sort_values(secondaryDimension)
g = sns.catplot(x="percentage", y=secondaryDimension, hue=primaryDimension, kind='bar', data=primaryDimensionPercent)
else:
sns.catplot(x="percentage", y='index', kind='bar', data=primaryDimensionPercent)
MakePercentageFrequencyTable(dataFrame=df,primaryDimension='Education', secondaryDimension='Gender')
# Question: I want to send in extraAggregatedField='Household Size' when I call the function such that
# it creates a secondary 'Household Size' axis at the top of the figure
# and aggregates/integrates the 'Household Size' column such that the following points are plotted
# against the secondary axis and positioned over the given bars:
#
# Female/College => 3
# Female/High School => 4
# Male/College => 3
# Male/High School => 4
陪伴而非守候
相关分类