Sam V
Sam V

Reputation: 21

Animation using plotly

I want to create an animation using plotly library. I need a randomly moving point (from [0,0]) which leaves a trace behing.
Here you can see a video of what I need. - https://i.sstatic.net/mzxeY.jpg

Upvotes: 1

Views: 343

Answers (1)

vestland
vestland

Reputation: 61094

The code snippet below will produce a Plotly Dash app that animates a form of Random Walk. How that walk will appear will depend entirely on what kind of random nunbers you base it on. Here I'm using two accumulated processes for the X and Y axes based on np.random.uniform. But you can easily change that to whatever random process you prefer.

Dash App after 2500 runs

enter image description here

Dash App after 5000 runs

enter image description here

Complete code:

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# data
np.random.seed(4)
Y = np.random.randint(low=-1, high=2, size=1).tolist()
X = np.random.randint(low=-1, high=2, size=1).tolist() 
df = pd.DataFrame({'X':X, 'Y':Y}, columns = ['X', 'Y'])
df.iloc[0]=0

# plotly app
app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("Random stumble"),
            dcc.Interval(
            id='interval-component',
            interval=1*1000, # in milliseconds
          
        ),
    dcc.Graph(id='graph'),
])

# Define callback to update graph
@app.callback(
    Output('graph', 'figure'),
    [Input('interval-component', "n_intervals")]
)
def streamFig(value):
    
    global df
   
    Y = np.random.randint(low=-1, high=2, size=1).tolist()
    X = np.random.randint(low=-1, high=2, size=1).tolist()  
    df2 = pd.DataFrame({'X':X, 'Y':Y}, columns = ['X', 'Y'])
    df = df.append(df2, ignore_index=True)#.reset_index()
    df3=df.copy()
    df3=df3.cumsum()
    fig = go.Figure(data=go.Scatter(x=df3['X'], y=df3['Y']))
    fig.update_layout(title = dict(text = 'x =' + str(X) + ', y ='+str(Y) + ', len = '+str(len(df))))
    #fig.update_layout(xaxis=dict(range=[-10,10]))
    #fig.update_layout(yaxis=dict(range=[-10,10]))
    return(fig)

app.run_server(mode='external', port = 8019, dev_tools_ui=True, debug=True,
              dev_tools_hot_reload =True, threaded=False)

Upvotes: 2

Related Questions