# 如何向 matplotlib/seaborn 条形图添加第二个轴并使辅助点与正确的条形对齐？

2023-08-22 10:48:35

## 1 回答

TA贡献1757条经验 获得超8个赞

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()

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')

• 1 回答
• 0 关注
• 3819 浏览

0/150