Параметры фильтрации для нескольких графиков в виде черточки - PullRequest
0 голосов
/ 21 сентября 2019

В настоящее время я работаю над графиками для моего проекта.У меня есть два кадра данных.Среди них один объясняет количество клиентов, а другой - финансовый объем продаж.Я хотел бы построить три различных графика, а именно: график рассеяния, гистограмма и круговая диаграмма для этих данных.

Но есть одна вещь, которую я не могу понять из этого.Здесь мне нужно получить три фильтра.Один - столбец данных, второй - график, третий - количество или число фин.Если пользователь нажимает на Login-Pie-Count, то должен отображаться только этот конкретный график или, если пользователь нажимает Approved-Bar-Fin_amount, то он должен отображаться, и наоборот.Я добавил выпадающие на страницу.Но я не могу отозвать результаты.Вот сценарий, который я разработал для графиков и образцов данных.

Branch,Login,Approved,Reject,Agreement,Disbursed,Cancelled, Total
Miyapur,2,2,0,4,9,0,17
Banjara Hills,1,2,0,0,4,2,7

Branch,Login_finamt,Approved_finamt,Agreement_finamt,Disbursed_finamt,Cancelled_finamt,Reject_finamt,Total_finamt
jeep-showroom,20.86 ,0 ,0 ,36.6 ,133 ,0 ,57.45
banjara-hills,14.79 ,0 ,0 ,0 ,0 ,0 ,14.79 


import dash
import flask
import dash_core_components as dcc
from werkzeug.middleware.dispatcher import DispatcherMiddleware
import dash_html_components as html
from werkzeug.serving import run_simple
from dash.dependencies import Input, Output
import plotly.graph_objs as go
from flask import Flask, render_template
import pandas as pd
import json

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
server = Flask(__name__)
app_1 = dash.Dash(__name__, server = server, url_base_pathname='/pride/branch_count/' )
app_2 = dash.Dash(__name__, server=server, url_base_pathname="/pride/branch_financial_amount/")

branch_count = pd.read_csv("dataframe_1.csv")
features = branch_count.columns
branchtypes = features[1:]  # don't want the Customer column


app_1.layout = html.Div([
    html.Div([
        # Here is the interactive component
        html.Div([
            dcc.Dropdown(
                id='first-drop_down',
                options=[{'label': i, 'value': i} for i in branchtypes],
                value='Login'
            ),
            html.Hr(),
            dcc.Dropdown(
                id='second-drop_down',
                options=[{'label': 'Count', 'value': 'c'},
                         {'label': 'Fin_amount' , 'value': 'F'}],
                value='c'
            ),
            html.Hr(),
            dcc.Dropdown(
                id='third-drop_down',
                options=[{"label": 'Bar Graph', 'value': 'BG'},
                         {"label": 'Scatter Plot', 'value': 'SP'},
                         {'label': 'Pie Chart', 'value': 'PC'}],
                value='BG'
            ),
            html.Hr()
        ], style={'width': '60%'})
    ]),
    html.Div([dcc.Graph(
        id='branch-graphic',
        figure={
            'data': [go.Scatter(
                x=branch_count['Branch'],
                y=[0, 0],
                mode='markers'
            )],
            'layout': go.Layout(
                title='Use the dropdown to display the chart ...',
                xaxis={'tickformat': 'd'},
                plot_bgcolor='#D3D3D3',
                paper_bgcolor='#D3D3D3',
                font = {
                    'color' : '#ff0000'
                }
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([dcc.Graph(
        id='branch-stacked',
        figure={
            'data': [go.Bar(
                x=branch_count['Branch'],
                y=branch_count['Login'],
                name='Login'
            ),
                go.Bar(
                    x=branch_count['Branch'],
                    y=branch_count['Approved'],
                    name='Approved'
                ),
                go.Bar(
                    x=branch_count['Branch'],
                    y=branch_count['Reject'],
                    name='Reject'
                ),
                go.Bar(
                    x=branch_count['Branch'],
                    y=branch_count['Agreement'],
                    name='Agreement'
                ),
                go.Bar(
                    x=branch_count['Branch'],
                    y=branch_count['Disbursed'],
                    name='Disbursed'
                ),
                go.Bar(
                    x=branch_count['Branch'],
                    y=branch_count['Cancelled'],
                    name='Cancelled'
                ),
            ],
            'layout': go.Layout(
                title='Customer Count in the Dealer from August',
                barmode='stack'
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([dcc.Graph(
        id='branch-pie',
        figure={
            'data': [go.Pie(
                labels=branch_count["Branch"].unique().tolist(), values=branch_count["Total"].tolist(),
                marker={'colors': ['#EF963B', '#C93277', '#349600', '#EF533B', '#57D4F1']},
                textinfo='label'
            )],
            'layout': go.Layout(
                title='Cases Reported Monthly',
                margin={"l": 300, "r": 300, },
                legend={"x": 1, "y": 0.7},
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([
        dcc.Markdown(children=markdown_text)
    ])
], style={'padding': 10})


# Here is the callback
@app_1.callback(
    Output('branch-graphic', 'figure'),
    [Input('first-drop_down', 'value'),
     Input('second-drop_down', 'value')])
def update_graphic(yaxis_branch, plots):
    return {
        'data': [go.Scatter(
            x=branch_count['Branch'],
            y=branch_count[yaxis_branch],
            mode='lines+markers',
            marker={
                'size': 20,
                'opacity': 0.8,
                'line': {'width': 1.0, 'color': 'white'}
            }
        )],
        'layout': go.Layout(
            title='{} in the Dealer by Customer Count, August 2019'.format(yaxis_branch),
            xaxis={'title': 'Branch'},
            yaxis={'title': yaxis_branch},
            hovermode='closest',
            plot_bgcolor='#D3D3D3',
            paper_bgcolor='#D3D3D3',
            font={
                'color': '#ff0000'
            }
        )
    }


branch_finamt = pd.read_csv("dataframe_2.csv")
features_finamt = branch_finamt.columns
branchtypes_finamt = features_finamt[1:]  # don't want the Customer column

app_2.layout = html.Div([
    html.Div([
        # Here is the interactive component
        html.Div([
            dcc.Dropdown(
                id='yaxis',
                options=[{'label': i, 'value': i} for i in branchtypes_finamt],
                value='Login_finamt',
            )
        ], style={'width': '60%'})
    ]),
    html.Div([dcc.Graph(
        id='branch-graphic',
        figure={
            'data': [go.Scatter(
                x=branch_finamt['Branch'],
                y=[0, 0],
                mode='markers'
            )],
            'layout': go.Layout(
                title='Use the dropdown to display the chart ...',
                xaxis={'tickformat': 'd'}
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([dcc.Graph(
        id='branch-stacked',
        figure={
            'data': [go.Bar(
                x=branch_finamt['Branch'],
                y=branch_finamt['Login_finamt'],
                name='Login'
            ),
                go.Bar(
                    x=branch_finamt['Branch'],
                    y=branch_finamt['Approved_finamt'],
                    name='Approved'
                ),
                go.Bar(
                    x=branch_finamt['Branch'],
                    y=branch_finamt['Reject_finamt'],
                    name='Reject'
                ),
                go.Bar(
                    x=branch_finamt['Branch'],
                    y=branch_finamt['Agreement_finamt'],
                    name='Agreement'
                ),
                go.Bar(
                    x=branch_finamt['Branch'],
                    y=branch_finamt['Disbursed_finamt'],
                    name='Disbursed'
                ),
                go.Bar(
                    x=branch_finamt['Branch'],
                    y=branch_finamt['Cancelled_finamt'],
                    name='Cancelled'
                ),
            ],
            'layout': go.Layout(
                title='Customer Count in the Dealer from August',
                barmode='stack'
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([dcc.Graph(
        id='branch-pie',
        figure={
            'data': [go.Pie(
                labels=branch_finamt["Branch"].unique().tolist(), values=branch_finamt["Total_finamt"].tolist(),
                marker={'colors': ['#EF963B', '#C93277', '#349600', '#EF533B', '#57D4F1']},
                textinfo='label'
            )],
            'layout': go.Layout(
                title='Cases Reported Monthly',
                margin={"l": 300, "r": 300, },
                legend={"x": 1, "y": 0.7},
            )
        }
    )
    ], style={'width': '70%', 'display': 'inline-block'}),
    html.Div([
        dcc.Markdown(children=markdown_text)
    ])
], style={'padding': 10})

# Here is the callback
@app_2.callback(
    Output('branch-graphic', 'figure'),
    [Input('yaxis', 'value')])
def update_graphic(yaxis_branch):
    return {
        'data': [go.Scatter(
            x=branch_finamt['Branch'],
            y=branch_finamt[yaxis_branch],
            mode='lines+markers',
            marker={
                'size': 20,
                'opacity': 0.8,
                'line': {'width': 1.0, 'color': 'white'}
            }
        )],
        'layout': go.Layout(
            title='{} in the Dealer by Customer Count, August'.format(yaxis_branch),
            xaxis={'title': 'Branch'},
            yaxis={'title': yaxis_branch},
            hovermode='closest'
        )
    }

@server.route('/')
@server.route('/hello')
def hello():
    return 'hello world!'

@server.route('/pride/branch_count')
def render_dashboard():
    return flask.redirect('/dash1')


@server.route('/pride/branch_financial_amount')
def render_reports():
    return flask.redirect('/dash2')


app = DispatcherMiddleware(server, {
    '/dash1': app_1.server,
    '/dash2': app_2.server
})

run_simple('127.0.0.1', 8080, app, use_reloader=True, use_debugger=True)

Может кто-нибудь помочь мне в этом.Любая помощь будет принята с благодарностью.Спасибо.

...