如何在 plotly 中将百分比添加到我的销售漏斗中?

问题描述 投票:0回答:1

面对在销售漏斗中显示百分比的问题。 我有下表:

visit_site_month reg_month 申请 游戏
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
import plotly.graph_objs as go

# Create a list of funnel steps
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='value+percent previous',
        marker={'color': '#44a9ff'}
    ),
    go.Funnel(
        name='Applications',
        x=merged_month_df['application'],
        y=merged_month_df['month'],
        textposition='inside',
        textinfo='value+percent previous',
        marker={'color': '#88c2ff'}
    ),
    go.Funnel(
        name='Game Plays',
        x=merged_month_df['game'],
        y=merged_month_df['month'],
        textposition='inside',
        textinfo='value+percent previous',
        marker={'color': '#c7e2ff'}
    )
]

# Create a dictionary with layout settings
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)
)

# Create a shape and display it
fig = go.Figure(data=steps, layout=layout)
fig.show()

我们得到一个这样的漏斗: enter image description here 如何使百分比显示为网站访问者的一小部分? 例如:enter image description here

我尝试更改 textinfo='value+percent previous',但没有帮助

python plotly plotly-python diagram
1个回答
0
投票

当您绘制每列数据时,我认为您无法获得每行的百分比。 如果你不介意使用 plotly.express,有一个参数可以让你定义文本。

计算数据框中的百分比,然后使用带有文本参数的 plotly.express。

import pandas as pd
import plotly.express as px

df = pd.DataFrame(dict(month= ['2022-09','2022-10'],
                  visit = [778, 843],
                  reg_month =[186, 219],
                  app = [40,68],
                  game = [2, 21]))


df2 = df.melt(id_vars = 'month', var_name='Type')
df2['prct'] = 100 * df2.value / df2.groupby('month')['value'].transform('max')

#plot, assign 'prct' column of the dataframe to text argument
fig = px.funnel(df2, x = 'value',y = 'month',color = 'Type', text = 'prct')
#format text: value <next line> percentage %
fig.update_traces(textposition='inside',texttemplate="%{x:.0f\n}<br>%{text:.2f}"+'%')

for d,dc in zip(fig.data,['#3b78e7','#44a9ff','#88c2ff','#c7e2ff']):
    d.marker.color= dc
fig.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.