Python 如何将第二个轴添加到matplotlib/seaborn条形图,并使辅助点与正确的条形图对齐?

Python 如何将第二个轴添加到matplotlib/seaborn条形图,并使辅助点与正确的条形图对齐?,python,matplotlib,charts,seaborn,axes,Python,Matplotlib,Charts,Seaborn,Axes,我编写了一个(新手)python函数(如下)来绘制一个由主维度和可能的辅助维度组成的条形图。例如,下图显示了达到特定教育水平的男女比例 问题:我如何在每个栏上覆盖该分组的家庭规模中值,例如,在大学/女性栏上放置一个表示值“3”的点。我所看到的例子中没有一个能准确地将点覆盖在正确的条上 我对这个非常陌生,所以非常感谢你的帮助 df = pd.DataFrame({'Student' : ['Alice', 'Bob', 'Chris', 'Dave', 'Edna', '

我编写了一个(新手)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

您必须使用轴级函数
sns.barplot()
sns.stripplot()
,而不是
catplot()
,这将创建一个新图形和一个
FaceGrid

大概是这样的:

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, ax=None):
    ax = plt.gca() if ax is None else ax
    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)
        ax = sns.barplot(x="percentage", y=secondaryDimension, hue=primaryDimension, data=primaryDimensionPercent, ax=ax)
    else:
        ax = sns.barplot(x="percentage", y='index', data=primaryDimensionPercent, ax=ax)
    
    if extraAggregatedField is not None:
        ax2 = ax.twiny()
        extraDimension = dataFrame.groupby([primaryDimension, secondaryDimension]).mean().reset_index(drop=False)
        ax2 = sns.stripplot(data=extraDimension, x=extraAggregatedField, y=secondaryDimension, hue=primaryDimension, 
                            ax=ax2,dodge=True, edgecolors='k', linewidth=1, size=10)


plt.figure()
MakePercentageFrequencyTable(dataFrame=df,primaryDimension='Education', secondaryDimension='Gender', extraAggregatedField='Household Size')

欢迎使用堆栈溢出!请花点时间阅读。您需要提供一个包含玩具数据集(请参阅)Thank You@DizietAsahi的。我重写了这个问题,希望能在本地重现,并且更清晰。