简体   繁体   English

Dash Plotly-如何使2个条件绘制直方图?

[英]Dash Plotly - How to make 2 conditions to plot a histogram?

I'm looking for a way to graph a histogram for data respecting 2 Dropdown . 我正在寻找一种方法来绘制直方图,以表示尊重2 Dropdown数据。 I have to choose the value of firstcall and the value of the secondcall in order to plot the histogram. 我必须选择firstcall的值和secondcall的值才能绘制直方图。 I don't find lot of literature on this subject I hope one of you have already face to this. 我没有关于这个主题的很多文献,我希望你们中的一个已经面对这个问题。

Please find an excel file with some data and the code I try bellow: 请找到一个包含一些数据和我在下面尝试的代码的excel文件:

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

df = pd.read_excel(
    "/Users/appelexcel.xlsx"
)

mgr_options = df["premierappel"].unique()
mgr_options_second = df["secondappel"].unique()

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

colors = {
    'background': '#FDFFFF',
    'text': '#0A25DC'
}

app.layout = html.Div(style={'backgroundColor': colors['background']},children=[
    html.H1(children='Call',
     style={
            'textAlign': 'center',
            'color': colors['text']
        }
        ),

    html.Div(
        [
            dcc.Dropdown(
                id="premierappel",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options],
                value='All First Call'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='secondcallgraph'), 
 #The first plot just give the 2nd call

    html.Div(
        [
            dcc.Dropdown(
                id="secondappel",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options_second],
                value='All Second Call'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='thirdcallgraph'), # second figure
])


@app.callback(
    dash.dependencies.Output('secondcallgraph', 'figure'),
    [dash.dependencies.Input('premierappel', 'value')])
def update_graph(premierappel):
    if premierappel == "All First Call":
        df_plot = df.copy()
    else:
        df_plot = df[df['premierappel'] == premierappel]

    #func=(lambda x: round(100*x.count()/df_plot.shape[0] ,2))
    pv = pd.pivot_table(
        df_plot,
        index=['Age_1_2'],
        columns=['secondappel'],
        values=['frequency_1_2'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'modification')], name='Modification')
    trace2 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'informations')], name='Informations')
    trace3 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'autres')], name='Autres')
    trace4 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'achat')], name='Achat')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Appel 2 / {}'.format(premierappel),
            xaxis=dict(
                title='Days after 1st Call'),
            yaxis=dict(
                title='Count'),
            barmode='stack')
    }

Second graph (on third call) 第二张图表(第三次通话)

My problem appears here, how can I tell him to take into account 2 conditions (one on first call and one on the second call qualification) ? 我的问题出现在这里,我如何告诉他考虑两个条件(一个在第一次通话中资格,一个在第二个通话资格中)?

@app.callback(
    dash.dependencies.Output('thirdcallgraph', 'figure'),
    [dash.dependencies.Input('premierappel', 'value'), dash.dependencies.Input('secondappel', 'value')])
def update_graph(premierappel,secondappel):
    if premierappel & secondappel == "All Second Call":
        df_plot = df.copy()
    else:
        df_plot = df[(df['premierappel']==premierappel) & (df['secondappel']==secondappel)]

    #func=(lambda x: round(100*x.count()/df_plot.shape[0] ,2))
    pv = pd.pivot_table(
        df_plot,
        index=['Age_2_3'],
        columns=['troisiemeappel'],
        values=['frequency_2_3'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'modification')], name='Modification')
    trace2 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'informations')], name='Informations')
    trace3 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'autres')], name='Autres')
    trace4 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'achat')], name='Achat')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Appel 2 / {}'.format(secondappel),
            xaxis=dict(
                title='Days after 2nd Call'),
            yaxis=dict(
                title='Count'),
            barmode='stack')
    }


if __name__ == '__main__':
    app.run_server(debug=True)

Thanks for your time ! 谢谢你的时间 !

Age_._. 年龄_。_。 : time between calls. :通话间隔时间。

Frequence : should be frequency but it's really random just to see how it's working. 频率:应该是频率,但实际上只是为了观察频率如何是随机的。

Please find the data above. 请在上面找到数据。 https://docs.google.com/spreadsheets/d/1u7E6GwJj1nsjOwIQIntcCWCKsczw36_iHPiEV2bjMcs/edit?usp=sharing https://docs.google.com/spreadsheets/d/1u7E6GwJj1nsjOwIQIntcCWCKsczw36_iHPiEV2bjMcs/edit?usp=sharing

I can't wrap my head around what it is supposed mean. 我无法理解到底是什么意思。 But here is what I can assume from the error messages I am getting: 但是,这是我可以从收到的错误消息中得出的结论:

File "pandas\_libs\index.pyx", line 672, inpandas._libs.index.BaseMultiIndexCodesEngine.get_loc

KeyError: ('frequency_2_3', 'modification')

That's it. 而已。

In your second callback you are assigning four traces. 在第二个回调中,您将分配四个跟踪。 But the variable (pandas.Series()) pv will only hold a single column (during my debugging trials). 但是变量(pandas.Series()) pv仅包含一个列(在我的调试试用期间)。

Assuming that the second callback is supposed to work as a filter: The solution might involve a If ... elif ... else block. 假定第二个回调应该用作过滤器:解决方案可能涉及If ... elif ... else块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM