簡體   English   中英

Plotly-Dash 實時圖表

[英]Plotly-Dash live chart

我剛開始學習破折號 plotly。 構建繪圖沒有問題。 我認為這是一個很棒的數據可視化庫。 但是我遇到了圖表中的數據沒有更新的事實。 我的數據在數據庫中,並且一直在被記錄。 我正在使用 pandas 進行渲染。 這是我的代碼:

import sqlite3
import pandas as pd
from datetime import datetime
import pytz
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html



timezone = pytz.timezone("Etc/UTC")
utc_from = datetime(2021, 3, 23, tzinfo=timezone)
#Создает новый файл , если он есть то просто подключается
base = sqlite3.connect('base_eurousd.db')

cur = base.cursor()

read_db = cur.execute('SELECT * FROM data_eurusd').fetchall()
df = pd.DataFrame(read_db)
#d = pd.read_sql("select * from data", db_conn)
print(df)


df[0] = pd.to_datetime(df[0], unit='ms')
df[3] = np.where(df[1].diff().lt(0)|df[2].diff().lt(0), df[3]*-1, df[3])


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

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

app.layout = html.Div(children=[
    html.H1(children='HELLO DASH'),
    html.H2(children='My first dash'),

    html.Div(children='''Dash : A web application framework for Python'''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x':df[0], 'y':df[1],  'name': 'BID', 'marker': {'color': 'red'}},
                {'x':df[0], 'y':df[2],  'name': 'ASK', 'marker': {'color': 'blue'}},
            ],
            'layout' : {
                'title': 'TEST'
            }
        }
    )
])
if __name__ == '__main__' :
    app.run_server(debug=True)

df output:

                   0        1        2  3
0      1623066946305  1.21623  1.21625  2
1      1623066946432  1.21622  1.21625  2
2      1623066947746  1.21621  1.21624  6
3      1623066949244  1.21621  1.21623  4
4      1623066949587  1.21621  1.21624  4
...              ...      ...      ... ..
85715  1623171716674  1.21840  1.21842  2
85716  1623171716808  1.21841  1.21843  6
85717  1623171717070  1.21841  1.21842  4
85718  1623171717419  1.21839  1.21841  6
85719  1623171717538  1.21838  1.21840  6

我的問題是:如何啟動應用程序並查看圖表的實時更新?

這不是最好的版本,但它可以讓你清楚地看到它是如何工作的

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import sqlite3
import pytz
import pandas as pd
import numpy as np
from datetime import datetime

app = dash.Dash(__name__)



points = 0
def test():
    global points
    points += 1

def get_value(n_intervals):
    timezone = pytz.timezone("Etc/UTC")
    utc_from = datetime(2021, 3, 23, tzinfo=timezone)
    base = sqlite3.connect('base_eurousd.db')
    cur = base.cursor()
    
    read_db = cur.execute('SELECT * FROM data_eurusd').fetchall()
    df = pd.DataFrame(read_db)
    # d = pd.read_sql("select * from data", db_conn)


    df[0] = pd.to_datetime(df[0], unit='ms')
    df[3] = np.where(df[1].diff().lt(0) | df[2].diff().lt(0), df[3] * -1, df[3])
    #print(df)
    return df


def serve_layout():
    return html.Div(
        children=[
            html.H4(children='Доска'),
            html.Div(id='my-id', children='''EURUSD'''),
            dcc.Graph(id='example-graph', animate=True, responsive=True),
            dcc.Interval(
                id='interval-component',
                interval=3 * 1000,
                n_intervals=0,
            ),
        ],
    )

app.layout = serve_layout

@app.callback(
    Output('example-graph','figure'),
    [Input('interval-component', 'n_intervals')])
def update_graph(n_intervals):
    df = get_value(n_intervals)
    test()
    return  \
        {
            'data': [
                {'x': df[0], 'y': df[1], 'type': 'line', 'name': 'BID'},
                {'x': df[0], 'y': df[2], 'type': 'line', 'name': 'ASK'},
            ],
            'layout': go.Layout(xaxis=dict(range=[min(df[0]),max(df[0])]),yaxis=dict(range=[min(df[1]),max(df[2])]),)
        }

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM