编写人口金字塔绘制函数时如何区分两个同名参数
人口金字塔自定义函数实现
核心解决思路:不用重名参数,按男性/女性两个分组维度拆分语义独立的形参,从命名上直接区分两个图例、两类人口数据的传参入口,从根源避免同名参数冲突。
函数参数说明
df: 绘图用的源数据DataFrameage_col: 年龄字段的列名,默认值为'Age'male_col: 男性人口统计值的列名,默认值为'Unmarried_Men'female_col: 女性人口统计值的列名,默认值为'Unmarried_Women'male_legend: 男性分组的图例名称,默认值为'Unmarried Men'female_legend: 女性分组的图例名称,默认值为'Unmarried Women'plot_title: 图表主标题,默认值为'Compare unmarried Men and Women'x_axis_title: X轴的标题文本,默认值为'Population in thousands'x_tick_range: X轴单侧最大刻度值,默认值为3000,函数会自动生成正负对称的刻度与标签
完整函数代码
import plotly.graph_objects as gp import numpy as np def plot_population_pyramid( df, age_col='Age', male_col='Unmarried_Men', female_col='Unmarried_Women', male_legend='Unmarried Men', female_legend='Unmarried Women', plot_title='Compare unmarried Men and Women', x_axis_title='Population in thousands', x_tick_range=3000 ): fig = gp.Figure() # 添加男性侧横向柱形 fig.add_trace( gp.Bar( y=df[age_col], x=df[male_col], name=male_legend, orientation='h' ) ) # 添加女性侧横向柱形,数值取负实现左右对称效果 fig.add_trace( gp.Bar( y=df[age_col], x=df[female_col] * -1, name=female_legend, orientation='h' ) ) # 自动生成对称X轴刻度 tick_step = 1000 tick_vals = np.arange(-x_tick_range, x_tick_range + tick_step, tick_step).tolist() tick_texts = [str(abs(val)) for val in tick_vals] # 更新布局配置 fig.update_layout( title=plot_title, barmode='overlay', bargroupgap=0, xaxis=dict( tickvals=tick_vals, ticktext=tick_texts, title=x_axis_title ) ) fig.show()
调用示例
直接使用默认参数绘图时,和参考代码效果完全一致:
plot_population_pyramid(df)
如果需要自定义图例、标题,直接传入对应参数即可,不会出现同名参数冲突的问题:
plot_population_pyramid( df, male_legend='已婚男性', female_legend='已婚女性', plot_title='已婚男女人口结构对比', x_axis_title='人口数(千人)' )
注:函数自动生成对称X轴刻度,不需要手动写死刻度值,适配不同量级的人口数据。
内容的提问来源于stack exchange,提问作者Phan
相关产品推荐
相关产品推荐

