Petrik
Petrik

Reputation: 827

Dash app, plotly chart data outside the chart area

I have written following code which updates Plotly Chart with some random values every 5 seconds, however after few seconds the new data is located outside the chart and is not visible. Is there an easy way to reset the axes everytime it's needed?

Also how can I make this responsive so it will auto-scale to full window?

import requests
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
from datetime import datetime
import json
import plotly.graph_objs as go
import random

# Create empty lists to store x and y values
x_values = []
y_values = []


# Initialize the dash app
app = dash.Dash()

app.layout = html.Div([
    dcc.Graph(id='live-graph', animate=True,responsive=True),
    dcc.Interval(
        id='graph-update',
        interval=5000,
        n_intervals=0
    ),
])

# Define the callback function
@app.callback(Output('live-graph', 'figure'), [Input('graph-update', 'n_intervals')])
def update_graph(n):

    current_value= random.randint(2000, 8000)


    # Get the current datetime
    x = datetime.now()
    x_values.append(x)

    # Get the response value and append it to the y_values list
    y = current_value
    y_values.append(y)

    # Create the line chart
    trace = go.Scatter(x=x_values, y=y_values)
    data = [trace]

    layout = go.Layout(title='Real-time Data',
                   xaxis=dict(title='Datetime'),
                   yaxis=dict(title='Value'))

    return go.Figure(data=data, layout=layout).update_layout(
        autosize=True,
        margin=dict(l=0, r=0, t=0, b=0)
    )

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

Many thanks!

Upvotes: 1

Views: 231

Answers (1)

Bench Vue
Bench Vue

Reputation: 9380

Using this method.

Fixed y axis range from 2000 to 8000

And x axis range find min and max every time.

    layout = go.Layout(title='Real-time Data',
                yaxis_range=[2000,8000],
                xaxis_range=[min(x_values),max(x_values)],
                xaxis=dict(title='Datetime'),
                yaxis=dict(title='Value'))
    
    return go.Figure(data=data, layout=layout).update_layout(
        autosize=True,
        margin=dict(l=0, r=0, t=50, b=50)
    )   

enter image description here

Upvotes: 1

Related Questions