基于SQL查询的Plotly Dash显示动态图数

时间:2019-01-03 22:16:27

标签: python plotly plotly-dash

我试图让该应用程序在用户更改日期输入时以网格格式显示多个图。到目前为止,这就是我所拥有的。虽然,当我现在运行该应用程序时,它仅显示一个图形,而不是全部图形。我不确定如何编写代码,以便所显示的图形数量是动态的,并且无论运行该应用程序的人在屏幕上仅占据足够的空间。

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import pyodbc
from datetime import datetime as dt

app = dash.Dash()

app.layout = html.Div(children=[
    html.Div(children='''
        Enter Date:
    '''),
    dcc.DatePickerSingle(id='date_picker_single', date=dt(2017, 12, 18)),
    html.Div(id='output-graphs'),
    ])


def connect_sql_server(driver, server, db):
    conn_sql_server = pyodbc.connect(
        r'DRIVER={' + driver + '};'
        r'SERVER=' + server + ';'
        r'DATABASE=' + db + ';'
        r'Trusted_Connection=yes;',
        autocommit=True
    )
    return conn_sql_server


@app.callback(
    Output(component_id='output-graphs', component_property='children'),
    [Input(component_id='date_picker_single', component_property='date')]
    )
def update_graphs(input_date):
    sql_conn = connect_sql_server('ODBC Driver 13 for SQL Server', 'Server', 'Database')
    cursor = sql_conn.cursor()
    cursor.execute(
        """ 
        exec QCMonotonicityGraphs ?
        """, [input_date])
    rows = cursor.fetchall()

    sql_data = []
    for row in rows:
        sql_data.append(list(row))
    labels = ['strike', 'last', 'call_put', 'title']
    df = pd.DataFrame.from_records(sql_data, columns=labels)

    unique_titles = df.title.unique()

    graphs = []

    for unique_title in unique_titles:
        title = unique_title
        call_strike = []
        call_last = []
        for row in rows:
            if row[2] == 'C' and row[3] == unique_title:
                call_strike.append(row[0])
                call_last.append(row[1])

        put_strike = []
        put_last = []
        for row in rows:
            if row[2] == 'P' and row[3] == unique_title:
                put_strike.append(row[0])
                put_last.append(row[1])

        graphs.append(dcc.Graph(
            id='example-graph',
            figure={
                'data': [
                    {
                        'x': call_strike,
                        'y': call_last,
                        'mode': 'lines+markers',
                        'name': 'call'
                    },
                    {
                        'x': put_strike,
                        'y': put_last,
                        'mode': 'lines+markers',
                        'name': 'put'
                    }
                ],
                'layout': {
                    'title': title
                }
            }
        ))

    return graphs


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

Example

0 个答案:

没有答案