如何在Plotly销售漏斗中显示基于网站访客的百分比?
解决Plotly漏斗图百分比相对初始访客显示的问题
Plotly默认的percent initial是基于整个漏斗的第一个系列(所有月份访客总和),而非单月自身的访客数;percent previous则是相对上一步骤的占比,都无法满足你需要的“各步骤百分比相对于当月网站访客”的需求。要实现该效果,需手动计算百分比并自定义漏斗的显示文本。
实现步骤
- 为数据框添加各步骤相对当月访客的百分比列,精确到指定小数位数
- 在每个
go.Funnel组件中,通过text参数自定义显示内容(数值+自定义百分比),并将textinfo设为'text'以启用自定义文本
修改后的完整代码
import plotly.graph_objs as go import pandas as pd # 初始化示例数据(如果已有merged_month_df可跳过此部分) data = [ ["2022-09",778,186,40,2], ["2022-10",843,219,68,21], ["2022-11",786,195,66,43], ["2022-12",805,200,65,47], ["2023-01",852,215,77,63], ["2023-02",32,9,3,3] ] merged_month_df = pd.DataFrame(data, columns=["month","visit_site_month","reg_month","application","game"]) # 计算各步骤相对当月访客的百分比,保留2位小数 merged_month_df['reg_pct'] = (merged_month_df['reg_month'] / merged_month_df['visit_site_month'] * 100).round(2) merged_month_df['app_pct'] = (merged_month_df['application'] / merged_month_df['visit_site_month'] * 100).round(2) merged_month_df['game_pct'] = (merged_month_df['game'] / merged_month_df['visit_site_month'] * 100).round(2) # 创建漏斗步骤 steps = [ go.Funnel( name='Visits', x=merged_month_df['visit_site_month'], y=merged_month_df['month'], textposition='inside', textinfo="value+percent initial", marker={'color': '#3b78e7'} ), go.Funnel( name='Registrations', x=merged_month_df['reg_month'], y=merged_month_df['month'], textposition='inside', textinfo='text', text=[f"{val} ({pct}%)" for val, pct in zip(merged_month_df['reg_month'], merged_month_df['reg_pct'])], marker={'color': '#44a9ff'} ), go.Funnel( name='Applications', x=merged_month_df['application'], y=merged_month_df['month'], textposition='inside', textinfo='text', text=[f"{val} ({pct}%)" for val, pct in zip(merged_month_df['application'], merged_month_df['app_pct'])], marker={'color': '#88c2ff'} ), go.Funnel( name='Game Plays', x=merged_month_df['game'], y=merged_month_df['month'], textposition='inside', textinfo='text', text=[f"{val} ({pct}%)" for val, pct in zip(merged_month_df['game'], merged_month_df['game_pct'])], marker={'color': '#c7e2ff'} ) ] # 布局设置 layout = go.Layout( title='Funnel Chart of Sales Dynamics', funnelmode='stack', showlegend=True, legend=dict(x=1.0, y=0.8), xaxis=dict(title='Month'), yaxis=dict(title='Number of Visitors'), margin=dict(l=100, r=100, t=100, b=100) ) fig = go.Figure(data=steps, layout=layout) fig.show()
关键说明
- 手动计算百分比保证了每个数值都是相对于当月
visit_site_month的占比,精准符合需求 - 通过列表推导式生成自定义文本,可灵活调整显示格式(比如修改小数位数、添加单位等)
textinfo='text'指定Plotly使用我们自定义的文本内容,替代默认的自动生成信息
内容的提问来源于stack exchange,提问作者Joker221
相关产品推荐
相关产品推荐

