Show Sidebar Hide Sidebar

Streaming to Multiple Traces in Python

Streaming in Plotly with Python

Check which version is installed on your machine and please upgrade if needed.

In [1]:
import plotly
plotly.__version__
Out[1]:
'1.9.10'

Now let's load the dependencies/packages that we need in order to get a simple stream going.

In [3]:
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import numpy as np

Overview

In this example we're going to stream to two different scatter traces. Moreover, we're going to provide seperate axes for each of these traces, assuming that they're on different scales.

Getting Set Up

Let's get at least two streaming tokens for this task.

In [4]:
stream_tokens = tls.get_credentials_file()['stream_ids']
token_1 = stream_tokens[-1]   # I'm getting my stream tokens from the end to ensure I'm not reusing tokens
token_2 = stream_tokens[-2]
print token_1
print token_2
0xhh453c6m
4lm5a0gsr8

Now let's create some stream id objects for each token.

In [5]:
stream_id1 = dict(token=token_1, maxpoints=60)
stream_id2 = dict(token=token_2, maxpoints=60)
In [ ]:
trace1 = go.Scatter(x=[], y=[], stream=stream_id1, name='trace1')
trace2 = go.Scatter(x=[], y=[], stream=stream_id2, yaxis='y2', name='trace2', marker=dict(color='rgb(148, 103, 189)'))

data = [trace1, trace2]
layout = go.Layout(
    title='Streaming Two Traces',
    yaxis=dict(
        title='y for trace1'
    ),
    yaxis2=dict(
        title='y for trace2',
        titlefont=dict(
            color='rgb(148, 103, 189)'
        ),
        tickfont=dict(
            color='rgb(148, 103, 189)'
        ),
        overlaying='y',
        side='right'
    )
)

fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='multple-trace-axes-streaming')

Now let's set up some stream link objects and start streaming some data to our plot

In [8]:
s_1 = py.Stream(stream_id=token_1)
s_2 = py.Stream(stream_id=token_2)

Start Streaming

In [ ]:
s_1.open()
s_2.open()

import time
import datetime
import numpy as np

k=10
i=0

while True:
    x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
    delta = np.random.randint(4,10)
    y = (np.cos(k*i/50.)*np.cos(i/50.)+np.random.randn(1))[0]
    s_1.write(dict(x=x,y=y))
    s_2.write(dict(x=x,y=(-delta*y)))
    time.sleep(0.8)
    i += 1
s_1.close()
s_2.close()
In [4]:
tls.embed('streaming-demos','124')
Out[4]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.