Example #1
0
def plot_stacked_funnel(events, steps, col=None, from_date=None, to_date=None, step_interval=0):
    """
    Function used for producing a funnel plot

    :param events: (DataFrame)
                    events dataframe

    :param steps: (list)
                    list containing funnel steps as strings

    :param col: (str)
                    column to be used for grouping the funnel dataframes

    :return: (plt.figure) funnel plot
    """

    # create list to append each trace to
    # this will be passed to "go.Figure" at the end
    data = []

    # if col is provided, create a funnel_df for each entry in the "col"
    if col:
        # generate dict of funnel dataframes
        dict_ = group_funnel_dfs(events, steps, col)
        title = 'Funnel plot per {}'.format(col)
    else:
        funnel_df = create_funnel_df(events, steps, from_date=from_date, to_date=to_date, step_interval=step_interval)
        dict_ = {'Total': funnel_df}
        title = 'Funnel plot'

    for t in dict_.keys():
        trace = go.Funnel(
            name=t,
            y=dict_[t].step.values,
            x=dict_[t].val.values,
            textinfo="value+percent previous"
        )
        data.append(trace)

    layout = go.Layout(margin={"l": 180, "r": 0, "t": 30, "b": 0, "pad": 0},
                       funnelmode="stack",
                       showlegend=True,
                       hovermode='closest',
                       plot_bgcolor='rgba(228, 222, 239, 0.65)',
                       title='Funnel Plot per {}'.format(col),
                       legend=dict(orientation="h",
                                   yanchor="bottom",
                                   y=1.02,
                                   xanchor="right",
                                   x=1,
                                   font=dict(
                                       size=12,
                                       color="black"),
                                   bgcolor="LightSteelBlue",
                                   bordercolor="Black",
                                   borderwidth=2
                                   )
                       )

    return go.Figure(data, layout)
Example #2
0
def update_funnel(ad_set1, ad_set2):
    '''
    Function to update funnel visual based on ad set selections
    Input: (first ad set selection, optional: second ad set selection)
    Output: Funnel visualization
    '''
    
    #Identify features to include in funnel visual
    funnel_features = ["Impressions", "Link Clicks", "Website Leads",
                       "Website Registrations Completed", 'Ad Set Name']
    #If only one ad set is selected, update chart title accordingly
    if not ad_set2:
        selected_ads = [ad_set1]
        title = 'Ad Set ' + str(ad_set1) + ' Conversion Cycle'
    #If two ad sets are selected, update chart title accordingly
    else:
        selected_ads = [ad_set1, ad_set2]
        title = 'Comparison of Ad Sets ' + str(ad_set1) + ' & ' \
            + str(ad_set2) + ' Conversion Cycles'
    
    #Filter data to only include ad sets selected with drop-downs
    data = ads[ads['Ad Set Name'].isin(selected_ads)]
    #Group data by ad set name and sum
    data = data[funnel_features].groupby('Ad Set Name').sum()
    #Define figure layout
    layout = go.Layout(title=dict(text=title, x=0.6),
                       legend_title_text='Ad Set')
    fig = go.Figure(layout=layout)
    #Add funnel plot to figure for first add set
    fig.add_trace(go.Funnel(
        name = ad_set1,
        y = data.loc[ad_set1,:].index,
        x = data.loc[ad_set1,:].values,
        textinfo = "value+percent initial"))
    #If second ad set is selected, add another trace to figure for that set
    if len(selected_ads) > 1:
        fig.add_trace(go.Funnel(
            name = ad_set2,
            y = data.loc[ad_set2,:].index,
            x = data.loc[ad_set2,:].values,
            textinfo = "value+percent initial"))
    return(dcc.Graph(id='funnel-1', figure=fig))
Example #3
0
def plot_new_funnel(phases, values):

    fig = go.Figure(go.Funnel(
        y = phases,
        x = values,
        textposition = "inside",
        textinfo = "value+percent initial",
        opacity = 0.85, marker = {"color": colors[:len(phases)],
                                 },
        connector = {"line": {"color": "royalblue", "dash": "dot", "width": 3}})
        )

    fig.show()
Example #4
0
def funnel_plot(df, steps, col=None):
    """
    Функция для построения воронки с помощью plotly
    Parameters
    ---------
    df : pandas.DataFrame
        Объект pandas df.
    steps : list
        Список исследуемых событий. Список необходимо формировать в порядке воронки, от стартового события, до завершающего.
    col : str
        Фича, по которой будет разделение воронки. Например - OS, воронка будет разделена на iOS и Android.
    
    Returns
    -------
    fig : plotly.graph_objs._figure.Figure
        В качестве вывода будет объект Figure библиотеки plotly
    """
    data = []

    if col:
        dict_ = funnel.stacking_funnel(df, steps, col)
        title = 'Воронка заявки в разрезе {}'.format(col)
    else:
        funnel_df = funnel.create_funnel_df(df, steps)
        dict_ = {'Total': funnel_df}
        title = 'Воронка заявки'

    for t in dict_.keys():
        trace = go.Funnel(
            name=t,
            y=dict_[t].step.values,
            x=dict_[t].val.values,
            textinfo='value+percent previous'
        )
        data.append(trace)
    
    layout = go.Layout(margin={"l": 180, "r": 0, "t": 30, "b": 0, "pad": 0},
                       funnelmode="stack",
                       showlegend=True,
                       hovermode='closest',
                       title=title,
                       legend=dict(orientation="v",
                                   bgcolor='#E2E2E2',
                                   xanchor='left',
                                   font=dict(
                                       size=12)
                                   )
                       )
    fig = go.Figure(data, layout)
    return fig
    def save_funnel(self):
        timeseries = data_obj.timeseries_data()

        fig = go.Figure(go.Funnel(
            x = [timeseries['totalconfirmed'].iloc[-1],timeseries['totalrecovered'].iloc[-1],
                timeseries['totaldeceased'].iloc[-1]],
            y = ["Total Cases", "Total Recovered",  "Deaths"],
            textposition = "inside",
            textinfo = "value",
            opacity = 0.8, 
            marker = {"color": [self.confirmed_color,self.recovered_color,self.death_color],
                    "line": {"width": 2.5, "color": 'Black'}},
            connector = {"line": {"color": "navy", "dash": "dot", "width": 2.5}}))
        fig.update_layout(
            template="simple_white",
            title={'text': "COVID19: Pandemic in India",'x':0.5,'y':0.9,       
                'xanchor': 'center','yanchor': 'top'})
        fig.update_layout(height=700, template='simple_white',width=600)
        return fig
Example #6
0
def update_graph_funnel(n_intervals):
    conn = MySQLdb.connect(host="localhost", user="******", db="qpipe")
    cursor = conn.cursor()
    cursor.execute('''SELECT COUNT(p.sales_cycle_id) as Total,
sc.name FROM projects as p 
RIGHT JOIN sale_cycles as sc 
ON p.sales_cycle_id = sc.id 
GROUP BY sc.id ORDER BY Total DESC''')
    rows = cursor.fetchall()
    cursor.close()

    df3 = pd.DataFrame([[ij for ij in i] for i in rows])
    df3.rename(columns={0: 'Total', 1: 'Name'}, inplace=True)

    funnel = []
    funnel.append(go.Funnel(
        y=df3['Name'],
        x=df3['Total'],
    ))

    return {
        'data': funnel,
    }
Example #7
0
                            'displayModeBar': False
                            },

                    )
        ], style={'width': '43%', 'display': 'inline-block','margin-top':'35px','margin-left':'68px'}, className="class_g3"),     

    # *************************************************************************


        html.Div([
            html.H5(''),
            dcc.Graph(
                id='g4',
                figure=go.Figure(go.Funnel(
                                y = df_Top5_Group['Group'].tolist(),
                                x = df_Top5_Group['Count'].tolist(),
                                
                                ),
	                			layout=go.Layout(title='Terrorism By Most Influential Groups')
                			),   
                    config={
                        'displayModeBar': False
                        },      
                    )
        ], style={'width': '43%', 'display': 'inline-block'}, className="class_g4"),     




    # ###########################################################################
Example #8
0
    if i == 0:
        funnel["单一转化率"][i] = 1.0
    else:
        funnel["单一转化率"][i] = funnel["人数"][i] / funnel["人数"][i - 1]

print("funnel", funnel)

# 绘制漏斗分析图
import plotly.express as px
import plotly.graph_objs as go

trace = go.Funnel(
    y=["点击", "收藏及加入购物车", "购买"],
    x=[funnel["人数"][0], funnel["人数"][1], funnel["人数"][2]],
    textinfo="value+percent initial",
    marker=dict(color=["deepskyblue", "lightsalmon", "tan"]),
    connector={"line": {
        "color": "royalblue",
        "dash": "solid",
        "width": 3
    }})
print("trace", trace)  #a dictionary for Funnel with all parameters above
data1 = [trace]
print("data1", data1)  #put funnel in a list
fig = go.Figure(
    data1)  #create a webpge http://127.0.0.1:57577/ and show the figure
fig.show()  #

# RFM 模型是数据分析中衡量客户价值和客户创利能力的一个重要模型。为什么叫做RFM模型呢?
# 因为我们会搜集用户三个方面的数据来综合评定用户的价值等级,而这三项数据分别就是这里的RFM:
# R(Recency)——最近一次购买的时间有多远
# F(Frequency)——最近一段时间内的消费频率
Example #9
0
                    md=5,
                    style={'padding':'0.5% 0.5% 0.5% 0.5%'}
                )
                    ]),
        
          #second row
                dbc.Row([
                  dbc.Col(
                    [
                       dcc.Graph(
                               id='FUN',

                                        figure = {'data':[

                       go.Funnel(
             y = bytype['type'].unique(),
             x = bytype['GROSS'])
            ],

                                        'layout':go.Layout(paper_bgcolor = '#ffffff', plot_bgcolor='#ffffff')}
                       ), html.H5("Part by Role",style={'text-align':'center','padding':'0.5% 0.5% 0.5% 0.5%'})

                    ],
                    md=6,
                ),
        dbc.Col([
                       dcc.Graph(
                               id='FUN1',

                                        figure = {'data':[
Example #10
0
                                y=1.02,
                                yanchor="bottom",
                                x=1,
                                xanchor="right",
                                orientation="h",
                                font=dict(size=10)))

fta = dict(data=trace2, layout=layout2)
############################################
#Funnel figure
dfp = dfp.reset_index()
trace3 = [
    go.Funnel(
        y=dfp["grade"],
        x=dfp[i],
        name=i,
        orientation="h",
        textposition="inside",
        textinfo="value+percent total",
    ) for i in genders
]

layout3 = go.Layout(title="Percentage of Degree Classifications by gender",
                    legend=dict(title=None,
                                y=1.02,
                                yanchor="bottom",
                                x=1,
                                xanchor="right",
                                orientation="h",
                                font=dict(size=10)))

ftgf = dict(data=trace3, layout=layout3)