def initPlot(stream_id1, stream_id2, graph_title, max_points=8000):
    print("Plotly Version=" + plotly.__version__)
    print("Setting plotly credentials...")
    tls.set_credentials_file(username=PLOTLY_USERNAME, api_key=PLOTLY_API_KEY)
    #stream_ids = tls.get_credentials_file()['stream_ids']

    ## 1. SETUP STREAM_ID OBJECT
    # Make instance of stream id object
    stream_1 = go.Stream(
        token=stream_id1,  # link stream id to 'token' key
        #maxpoints=max_points      # keep a max of 80 pts on screen
    )

    stream_2 = go.Stream(
        token=stream_id2,  # link stream id to 'token' key
        #maxpoints=max_points      # keep a max of 80 pts on screen
    )

    # Initialize trace of streaming plot_init by embedding the unique stream_id
    trace1 = go.Scatter(
        x=[],
        y=[],
        name='高溫',
        mode='lines+markers+text',
        line=dict(shape='spline', color='rgb(255, 128, 0)'),
        stream=stream_1  # (!) embed stream id, 1 per trace
    )

    trace2 = go.Scatter(
        x=[],
        y=[],
        name='低溫',
        mode='lines+markers+text',
        line=dict(shape='spline', color='rgb(102, 178, 255)'),
        stream=stream_2  # (!) embed stream id, 1 per trace
    )

    data = go.Data([trace1, trace2])

    # Add title to layout object
    layout = go.Layout(title=graph_title,
                       xaxis=dict(title='日期 (年/月/日)',
                                  showgrid=False,
                                  showline=True,
                                  linewidth=2,
                                  tickwidth=2),
                       yaxis=dict(
                           title='溫度 (°C)',
                           showgrid=True,
                           showline=False,
                       ))

    # Make a figure object
    fig = go.Figure(data=data, layout=layout)

    # Send fig to Plotly, initialize streaming plot_init, open new tab
    py.plot(fig, filename=graph_title)
Exemplo n.º 2
0
def initialize_graph():
    global stream_1
    global s

    tls.set_credentials_file(username='******',
                             api_key='9pjer55x5e',
                             stream_ids=['efzmil96bw'])
    stream_id = tls.get_credentials_file()['stream_ids'][0]

    stream_1 = go.Stream(
        token=stream_id,  # link stream id to 'token' key
        maxpoints=80  # keep a max of 80 pts on screen
    )

    # pick up where we left off
    x_data = ab.get_column('time', 'prices', 'test_table.sqlite')
    y_data = ab.get_column('last', 'prices', 'test_table.sqlite')

    # some magic that makes the plot and uploads it to the plotly hosting site
    trace0 = go.Scatter(x=x_data, y=y_data, stream=stream_1)
    data = [trace0]
    layout = go.Layout(xaxis=dict(showticklabels=False))
    fig = go.Figure(data=data, layout=layout)
    unique_url = py.plot(fig, filename='basic-line', auto_open=False)
    # open stream connection
    s = py.Stream(stream_id)
    s.open()
Exemplo n.º 3
0
    def setup_metric_streams(self, local_stream_ids, metric_name, num_channels):

        for i in range(num_channels):
            stream_id = local_stream_ids[i]
            self.stream_ids.append(stream_id)
            py_stream = py.Stream(stream_id)
            py_stream.open()
            self.py_streams.append(py_stream)

            go_stream = go.Stream(token=stream_id, maxpoints=self.max_points)
            self.go_streams.append(go_stream)

        traces = []
        for i in range(num_channels):
            channel_name = "channel_%s" % i
            go_stream = self.go_streams[i]

            trace = go.Scatter(
                x=[],
                y=[],
                mode='splines',
                stream=go_stream,
                name=channel_name
            )
            traces.append(trace)

        data = go.Data(traces)
        layout = go.Layout(title=metric_name)
        fig = go.Figure(data=data, layout=layout)
        py.iplot(fig, filename=metric_name)
Exemplo n.º 4
0
def getTraces():
    stream_ids = tools.get_credentials_file()['stream_ids']
    stream_ids = stream_ids[:max_streams]
    traces = list()
    for stream_id in stream_ids:
        stream = go.Stream(token=stream_id, maxpoints=200)
        trace = go.Scatter(
            x=[],
            y=[],
            mode='lines+markers',
            stream=stream)
        traces.append(trace)
    return stream_ids, traces
def GPSTrack_setup():

    stream_id = stream_ids[0]
    stream_1 = go.Stream(
        token=stream_id,  # link stream id to 'token' key
        maxpoints=200)
    trace1 = go.Scatter(
        x=[],
        y=[],
        mode='markers',
        stream=stream_1  # (!) embed stream id, 1 per trace
    )

    data = go.Data([trace1])

    layout = go.Layout(title='GPS Track')

    fig = go.Figure(data=data, layout=layout)

    py.iplot(fig, filename='python-streaming')

    GPSTrack_plot = py.Stream(stream_id)

    return GPSTrack_plot
def TrueWind_setup():

    stream_id = stream_ids[1]
    stream_1 = go.Stream(
        token=stream_id,  # link stream id to 'token' key
        maxpoints=200)
    trace1 = go.Scatter(
        x=[],
        y=[],
        mode='lines+markers',
        stream=stream_1  # (!) embed stream id, 1 per trace
    )

    data = go.Data([trace1])

    layout = go.Layout(title='True Wind Speed')

    fig = go.Figure(data=data, layout=layout)

    py.iplot(fig, filename='python-true-wind-speed')

    s = py.Stream(stream_id)

    return s
Exemplo n.º 7
0
maxpoints = 10000
streamit = False

stream = []

if streamit:
    stream_id = ""  # Put your own token

    trace1 = py_gr.Scatter(x=[],
                           y=[],
                           xaxis=dict(title="Game"),
                           yaxis=dict(title="Score"),
                           mode='line',
                           name="Game",
                           stream=py_gr.Stream(token=stream_id,
                                               maxpoints=maxpoints))

    data = go.Data([trace1])
    layout = go.Layout(title='Martins stupid PhD algorithm')
    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, auto_open=False)

    stream = py.Stream(stream_id)
    stream.open()

for game in range(maxpoints):
    print("game:", game)

    scores.append(Play())
    print(scores[-1])
    if streamit:
Exemplo n.º 8
0
def setup_streams(number, maxpoints):
    stream_ids = tls.get_credentials_file()['stream_ids']
    for i in range(0, number):
        stream_id_i = stream_ids[i]
        stream_i = go.Stream(token=stream_id_i, maxpoints=maxpoints)
        streams.append(stream_i)
Exemplo n.º 9
0
import plotly.graph_objs as go
import plotly.plotly as py

from config import stream_tokens

pie_stream_id = stream_tokens[-1]
pie_stream = go.Stream(token=pie_stream_id)

transactions_pie_trace = go.Pie(labels=[],
                                values=[],
                                textfont=dict(size=20),
                                hoverinfo='label+percent',
                                textinfo='percent',
                                stream=pie_stream)

transactions_pie_url = py.plot([transactions_pie_trace],
                               filename='Transactions by Location (last period)',
                               fileopt="overwrite",
                               auto_open=False)

transactions_pie_stream = py.Stream(pie_stream_id)
Exemplo n.º 10
0
import plotly
import numpy as np
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go

plotly.tools.set_credentials_file(username='******',
                                  api_key='h5qictce9t',
                                  stream_ids=('wzwtxkdhnp', '9ovqspax14'))
stream_ids = plotly.tools.get_credentials_file()['stream_ids']

stream_id = stream_ids[0]

stream_1 = go.Stream(token=stream_id, maxpoints=80)

trace1 = go.Scatter(x=[], y=[], stream=stream_1)
data = go.Data([trace1])

layout = go.Layout(title='Time Series')
fig = go.Figure(data=data, layout=layout)
py.plot(fig, filename='python-streaming')

s = py.Stream(stream_id)
s.open()

import datetime
import time

i = 0
k = 5
Exemplo n.º 11
0
def setupPlotly(points):
    '''
    Sets up plotly graph to write to
    :param points: <int> of max number of points to keep plotted on graph
    :return: Plotly Stream object
    '''

    # Setup plotly
    stream_ids = tls.get_credentials_file()['stream_ids']

    # Get stream id from stream id list
    stream_id = stream_ids[0]

    # Make instance of stream id object
    stream_1 = go.Stream(
        token=stream_id,  # link stream id to 'token' key
        maxpoints=points  # keep a max of 80 pts on screen
    )

    # Initialize trace of streaming plot by embedding the unique stream_id
    trace1 = go.Scatter(
        x=[],
        y=[],
        mode='lines',
        stream=stream_1  # (!) embed stream id, 1 per trace
    )

    data = go.Data([trace1])

    # Add title to layout object
    layout = go.Layout(
        title='Twitter Overwatch Sentiment',
        xaxis=dict(
            title='Date & Time',
            titlefont=dict(
                size=18,
                color='#7f7f7f'
            )
        ),
        yaxis=dict(
            title='Aggregate Sentiment',
            titlefont=dict(
                size=18,
                color='#7f7f7f'
            )
        )
    )
    # Make a figure object
    fig = go.Figure(data=data, layout=layout)

    # Send fig to Plotly, initialize streaming plot, open new tab
    py.iplot(fig, filename='python-streaming')

    # We will provide the stream link object the same token that's associated with the trace we wish to stream to
    stream_object = py.Stream(stream_id)

    # We then open a connection
    stream_object.open()

    time.sleep(5)

    return stream_object
Exemplo n.º 12
0
    def __init__(self, chart_type, window_size=20):
        """
        INPUT:
            - chart_type: 'line', 'pie', 'bar'
            - window_size: how many data points to keep track of
        """
        # 2 stream id
        # api_cred.yml looks like this:
        # plotly:
        #     username: xxxx
        #     api_key: xxxx
        #     stream_ids:
        #         - xxxx
        #         - xxxx
        #         - xxxxx
        credentials = yaml.load(open(expanduser('tristan_cred.yml')))
        plotly.tools.set_credentials_file(
            **credentials['plotly'])  # plotly credentials

        stream_ids = tls.get_credentials_file()['stream_ids']

        self.ids = {
            'line': stream_ids[0],
            'pie': stream_ids[1],
            'bar': stream_ids[2]
        }
        self.traces = {
            'line': {
                'stream_id':
                self.ids['line'],
                'trace':
                go.Scatter(x=[],
                           y=[],
                           mode='lines+markers',
                           marker=dict(color="black"),
                           stream=go.Stream(token=self.ids['line'],
                                            maxpoints=80),
                           name='Average Score',
                           showlegend=False),
                'title':
                'Meetup RSVP Recent Total Count',
                'filename':
                'line-streaming'
            },
            'pie': {
                'stream_id':
                self.ids['pie'],
                'trace':
                go.Pie(
                    labels=['yes', 'no', 'other'],
                    values=[100, 50, 20],
                    domain=dict(x=[0, 1]),
                    #text=['yes', 'no', 'other'],
                    stream=go.Stream(token=self.ids['pie'], maxpoints=80),
                    sort=False),
                'title':
                'Meetup RSVP Running Response Count',
                'filename':
                'pie-streaming'
            },
            'bar': {
                'stream_id':
                self.ids['bar'],
                'trace':
                go.Bar(
                    x=[],
                    y=[],
                    # xaxis='x2',
                    # yaxis='y2',
                    marker=dict(color="blue"),
                    name='Dynamic Bar',
                    stream=go.Stream(token=self.ids['bar'], maxpoints=80),
                    showlegend=False),
                'title':
                'Meetup RSVP Recent Top Event',
                'filename':
                'bar-streaming'
            }
        }
        self.WIN_SIZE = window_size
        self.streams = {}
        self.chart_url = None

        # self.init_interview_stream()
        self.init_stream(chart_type=chart_type)
import plotly.graph_objs as go
import plotly.plotly as py
from plotly.graph_objs import *

from config import mapbox_access_tokens, stream_tokens

# Maps plot streaming

# Stream definition
maps_stream_token = stream_tokens[-2]
maps_stream_id = go.Stream(token=maps_stream_token, maxpoints=100000)
mapbox_access_token = mapbox_access_tokens[-1]

# Trace
maps_stream_trace = Data([
    Scattermapbox(lat=[],
                  lon=[],
                  mode='markers',
                  marker=Marker(size=6, color='rgb(0, 255, 0)'),
                  stream=maps_stream_id)
])

# Layout
maps_stream_layout = dict(autosize=True,
                          hovermode='closest',
                          mapbox=dict(accesstoken=mapbox_access_token,
                                      bearing=0,
                                      center=dict(lat=51.4974948,
                                                  lon=-0.13565829999993184),
                                      pitch=0,
                                      zoom=10))
Exemplo n.º 14
0
import numpy as np
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import pandas as pd

import datetime
import time

stream_ids = tls.get_credentials_file()['stream_ids']
print stream_ids

# Make instance of stream id object
stream_1 = go.Stream(
    token=stream_ids[0],  # link stream id to 'token' key
    maxpoints=80  # keep a max of 80 pts on screen
)
# Make instance of stream id object
stream_2 = go.Stream(
    token=stream_ids[1],  # link stream id to 'token' key
    maxpoints=80  # keep a max of 80 pts on screen
)
# Make instance of stream id object
stream_3 = go.Stream(
    token=stream_ids[2],  # link stream id to 'token' key
    maxpoints=80  # keep a max of 80 pts on screen
)
# Make instance of stream id object
stream_4 = go.Stream(
    token=stream_ids[3],  # link stream id to 'token' key
    maxpoints=80  # keep a max of 80 pts on screen
Exemplo n.º 15
0
import socket
import json
import datetime
import random
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.graph_objs import *
plotly.tools.set_credentials_file(username='******',
                                  api_key='VhSOVBTQMUDQ3hqlyLRr')

plotly.tools.set_config_file(world_readable=True, sharing='public')

# Make instance of stream id object
stream_1 = go.Stream(
    token='xfto8kd7cp',  # link stream id to 'token' key
    maxpoints=80  # keep a max of 80 pts on screen
)

trace1 = go.Scatter(x=[], y=[], mode="lines + markers", stream=stream_1)

data = go.Data([trace1])

layout = go.Layout(title='Time Series')

# Make a figure object
fig = go.Figure(data=trace1, layout=layout)

# Send fig to Plotly, initialize streaming plot, open new tab
py.iplot(fig, filename='python-streaming')

# We will provide the stream link object the same token that's associated with the trace we wish to stream to
print "Creating interval timer. This step takes almost 2 minutes on the Raspberry Pi..."
#create timer that is called every n seconds, without accumulating delays as when using sleep
scheduler = BackgroundScheduler()
scheduler.add_job(write_hist_value_callback, 'interval', seconds=sec_between_log_entries)
scheduler.start()
print "Started interval timer which will be called the first time in {0} seconds.".format(sec_between_log_entries);

# setting the plot streaming
stream_ids = tls.get_credentials_file()['stream_ids']
# Get stream id from stream id list 
stream_id_0 = stream_ids[0]
stream_id_1 = stream_ids[0]

# Make instance of stream id object 
stream_0 = go.Stream(
    token=stream_id_0,  # (!) link stream id to 'token' key
    maxpoints= 24 * 3600 / sec_between_stream_entries     # (!) keep a max of pts on screen
)

# Initialize trace of streaming plot by embedding the unique stream_id
trace_0 = go.Scatter(
    x=[],
    y=[],
    mode='lines+markers',
    stream=stream_0         # (!) embed stream id, 1 per trace
)

data = go.Data([trace_0])

# Add title to layout object
layout = go.Layout(title='Leaving Room Temperature (' +  degree_sign + 'C)')
Exemplo n.º 17
0
    def graph_issues_by_component(self,
                                  stats,
                                  table_title='Issues by Component (High/Med)',
                                  table_filename='tower_issues_by_component',
                                  maxpoints=60,
                                  build_table=False):  # 60 days
        # Confirm there are enough stream ids
        print "Confirm have enough stream ids"
        components = sorted(stats.keys())
        num_components = len(components)
        assert len(self.stream_tokens) >= num_components, \
            "Not enough plotly stream keys to plot data. Found %s (needed %s)" % \
            (len(self.stream_tokens), num_components)

        stream_ids = []
        for index in range(num_components):
            stream = go.Stream(token=self.stream_tokens[index],
                               maxpoints=maxpoints)
            stream_ids.append(stream)

        # Build Table
        if build_table:
            print "Building plot"
            traces = []
            for index in range(num_components):
                name = components[index].replace(self.component_tag,
                                                 '')  # Strip component prefix
                trace = go.Scatter(
                    x=[],
                    y=[],
                    stream=stream_ids[index],
                    name=name,
                    marker=dict(
                        color=self.colors[index]))  # mode='lines+markers'
                traces.append(trace)
            layout = go.Layout(title=table_title)
            fig = go.Figure(data=traces, layout=layout)

            url = py.plot(fig, filename=table_filename)
            print "Graph url: ", url

        # Create streams
        print "Creating streams"
        streams = []
        for index in range(num_components):
            stream = py.Stream(stream_id=self.stream_tokens[index])
            streams.append(stream)

        # Open streams
        print "Opening streams"
        for index in range(num_components):
            streams[index].open()

        # Write data
        print "Writing data"
        for index in range(num_components):
            x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
            component = components[index]
            y = stats[component]
            streams[index].write(dict(x=x, y=y))

        # Close streams
        print "Closing streams"
        for index in range(num_components):
            streams[index].close()
Exemplo n.º 18
0
    def graph_issues_by_priority(self,
                                 stats,
                                 table_title='Issues by Severity',
                                 table_filename='tower_issues_by_priority',
                                 maxpoints=60,
                                 build_table=False):  # 60 days
        # Confirm there are enough stream ids
        print "Confirm have enough stream ids"

        def priority_weight(priority):
            '''Hack to sort keys logically instead of alphabetically'''
            weight = {
                'priority:high': 0,
                'priority:medium': 1,
                'priority:low': 2
            }
            if priority in weight.keys():
                return weight[priority]
            return 0

        priority_levels = sorted(stats.keys(), key=priority_weight)
        num_priority_levels = len(priority_levels)
        assert len(self.stream_tokens) >= num_priority_levels, \
            "Not enough plotly stream keys to plot data. Found %s (needed %s)" % \
            (len(self.stream_tokens), num_priority_levels)

        stream_ids = []
        for index in range(num_priority_levels):
            stream = go.Stream(token=self.stream_tokens[index],
                               maxpoints=maxpoints)
            stream_ids.append(stream)

        # Build Table
        if build_table:
            print "Building plot"
            traces = []
            for index in range(num_priority_levels):
                name = priority_levels[index].replace(
                    self.priority_tag, '')  # Strip priority prefix
                trace = go.Scatter(
                    x=[],
                    y=[],
                    stream=stream_ids[index],
                    name=name,
                    marker=dict(
                        color=self.colors[index]))  # mode='lines+markers'
                traces.append(trace)
            layout = go.Layout(title=table_title)
            fig = go.Figure(data=traces, layout=layout)

            url = py.plot(fig, filename=table_filename, show_link=False)
            print "Graph url: ", url

        # Create streams
        print "Creating streams"
        streams = []
        for index in range(num_priority_levels):
            stream = py.Stream(stream_id=self.stream_tokens[index])
            streams.append(stream)

        # Open streams
        print "Opening streams"
        for index in range(num_priority_levels):
            streams[index].open()

        # Write data
        print "Writing data"
        for index in range(num_priority_levels):
            x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
            priority = priority_levels[index]
            y = stats[priority]
            streams[index].write(dict(x=x, y=y))

        # Close streams
        print "Closing streams"
        for index in range(num_priority_levels):
            streams[index].close()
def initGraph():
    # get list of all your stream ids
    stream_ids = tls.get_credentials_file()['stream_ids']

    # Get stream id from stream id list
    stream_id1 = stream_ids[0]

    # Make instance of stream id object
    stream_1 = go.Stream(
        token=stream_id1,  # link stream id to 'token' key
        maxpoints=20  # keep a max of 5 pts on screen
    )

    # Initialize trace of streaming plot by embedding the unique stream_id
    trace1 = go.Scatter(
        x=[],
        y=[],
        mode='lines+markers',
        stream=stream_1  # (!) embed stream id, 1 per trace
    )

    data = [trace1]
    # Add title to layout object
    layout = {
        'title':
        'example lample mample',
        'xaxis': {
            'range': [0, 300]
        },
        'yaxis': {
            'range': [0, 300]
        },
        'shapes': [
            {
                'type': 'line',
                'x0': 0,
                'y0': 0,
                'x1': 300,
                'y1': 0,
                'line': {
                    'color': 'rgb(55, 128, 191)',
                    'width': 3,
                },
            },
            {
                'type': 'line',
                'x0': 0,
                'y0': 0,
                'x1': 0,
                'y1': 300,
                'line': {
                    'color': 'rgb(55, 128, 191)',
                    'width': 3,
                },
            },
            {
                'type': 'line',
                'x0': 300,
                'y0': 0,
                'x1': 300,
                'y1': 300,
                'line': {
                    'color': 'rgb(55, 128, 191)',
                    'width': 3,
                },
            },
            {
                'type': 'line',
                'x0': 0,
                'y0': 300,
                'x1': 300,
                'y1': 300,
                'line': {
                    'color': 'rgb(55, 128, 191)',
                    'width': 3,
                },
            },
        ]
    }

    # Make a figure object
    fig = {'data': data, 'layout': layout}

    # Send fig to Plotly, initialize streaming plot, open new tab
    py.plot(fig, filename='python-streaming')

    # We will provide the stream link object the same token that's associated with the trace we wish to stream to
    s_1 = py.Stream(stream_id1)

    return s_1
Exemplo n.º 20
0
import plotly.plotly as py
import plotly.graph_objs as go
import datetime 
import time 
import numpy as np   

#py.sign_in('cebeka', '475knde90n') #username, apikey
#stream_id = 'rrbzcid5ty' # token
py.sign_in('adrienPlotly', '2vzts6z07f')
stream_id = 'u3pvpjla4o'
stream1 = go.Stream(token=stream_id, maxpoints=60)
plotUrl = py.plot(go.Data([go.Scatter(x=[], y=[], stream=stream1)]), filename="test", auto_open=False, sharing='public', fileopt='new')
print(plotUrl)
s = py.Stream(stream_id)
s.open() # Open the stream
 
i = 0    # a counter
k = 5    # some shape parameter
n = 0
# Delay start of stream by 5 sec (time to switch tabs)
time.sleep(5)
 
while True:
    # Current time on x-axis, random numbers on y-axis
    x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
    y = (np.cos(k*i/50.)*np.cos(i/50.)+np.random.randn(1))[0] 
    # Send data to your plot
    s.write(dict(x=x, y=y))  
    print(n)
    n = n+1
    #     Write numbers to stream to append current data on plot,
Exemplo n.º 21
0
from os.path import abspath, dirname, join

json_path = join(dirname(abspath(__file__)), 'config.json')

# Parse the configuration
with open(json_path) as config_file:
    plotly_user_config = json.load(config_file)

# Sign in to plotly
py.sign_in(plotly_user_config["plotly_username"],
           plotly_user_config["plotly_api_key"])

stream_id = plotly_user_config['plotly_streaming_tokens'][4]

stream_config = go.Stream(token=stream_id, maxpoints=1)

data = [
    go.Scatter(x=[0.5],
               y=[0.5],
               stream=stream_config,
               marker=dict(size=60,
                           color='rgba(152, 0, 0, .8)',
                           line=dict(width=2, color='rgb(0, 0, 0)')))
]
layout = go.Layout(
    # dragmode='select',
    xaxis=dict(
        range=[0, 3],
        dtick=1,
        fixedrange=True,
Exemplo n.º 22
0
        1: "CH4 Concentration (ppm)",
        2: "LPG Concentration (ppm)",
        3: "CO2 Concentration (ppm) ",
        4: "Dust Concentration (micrograms/m3)",
        5: "Temperature (degree C)",
        6: "Humidity (%)",
    }.get(x, "none")  # "none" is default if x not found


# Get stream id from stream id list
for i in range(0, 3):
    stream_id[i] = stream_ids[i]

    # Make instance of stream id object
    stream_obj[i] = go.Stream(
        token=stream_id[i],  # link stream id to 'token' key
        maxpoints=80  # keep a max of 80 pts on screen
    )

    # Initialize trace of streaming plot by embedding the unique stream_id
    trace[i] = go.Scatter(
        x=[],
        y=[],
        mode='lines+markers',
        stream=stream_obj[i]  # (!) embed stream id, 1 per trace
    )

    data = go.Data([trace[i]])

    # Add title to layout object
    layout = go.Layout(title=map_sensor_id_to_title(i + 1))
Exemplo n.º 23
0
# Parse the configuration
with open(json_path) as config_file:
    plotly_user_config = json.load(config_file)

# Sign in to plotly
py.sign_in(plotly_user_config["plotly_username"],
           plotly_user_config["plotly_api_key"])

# Here we get the 4 stream IDs
stream_id1 = plotly_user_config['plotly_streaming_tokens'][0]
stream_id2 = plotly_user_config['plotly_streaming_tokens'][1]
stream_id3 = plotly_user_config['plotly_streaming_tokens'][2]
stream_id4 = plotly_user_config['plotly_streaming_tokens'][3]

# Create the proper stream objects
stream_config_1 = go.Stream(token=stream_id1, maxpoints=200)
stream_config_2 = go.Stream(token=stream_id2, maxpoints=200)
stream_config_3 = go.Stream(token=stream_id3, maxpoints=200)
stream_config_4 = go.Stream(token=stream_id4, maxpoints=200)

plot1 = go.Scatter(x=[], y=[], stream=stream_config_1, name='Humidity (%)')
plot2 = go.Scatter(x=[], y=[], stream=stream_config_2, name='Temperature (C)')
plot3 = go.Scatter(x=[], y=[], stream=stream_config_3, name='VIS')
plot4 = go.Scatter(x=[], y=[], stream=stream_config_4, name='IR')

# Create a plot
url1 = py.plot([plot1, plot2],
               filename='Arduino Sensors data - Area conditions',
               fileopt='overwrite',
               auto_open=False)
Exemplo n.º 24
0
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
import numpy as np
import time
import datetime
import random
import sentiment

py.sign_in('SamarthJain', 'zse4msy081')

stream_ids = tls.get_credentials_file()['stream_ids']
stream_id = stream_ids[0]
# Make instance of stream id object
stream_1 = go.Stream(
    token=stream_id,  # link stream id to 'token' key
    maxpoints=100  # keep a max of 80 pts on screen
)

# Initialize trace of streaming plot by embedding the unique stream_id
trace1 = go.Scatter(
    x=[],
    y=[],
    mode='lines+markers',
    stream=stream_1  # (!) embed stream id, 1 per trace
)

data = go.Data([trace1])

# Add title to layout object
layout = go.Layout(title='Time Series')
Exemplo n.º 25
0

        
Exemplo n.º 26
0
username = '******' // 입력
api_key = "1234567"; // 입력

py.sign_in(username, api_key);



size = len(stream_ids);

colorArray = ['red','blue','green']
streamArray = [];
traceArray = [];

streamingServerArray = [];
for i in range(0,size):
    streamArray.append(go.Stream(token = stream_ids[i], maxpoints = 80));
    traceArray.append(go.Scatter(go.Scatter(x=[],y=[], mode ='lines+markers', stream= streamArray[i], marker = { 'color' : colorArray[i%3]}, name = 'Server'+str(i) )));
    streamingServerArray.append(py.Stream(stream_ids[i]));

data = go.Data(traceArray);

layout = go.Layout(title='Traffic Level');

fig = go.Figure(data=data, layout= layout);

py.plot(fig,filename='Traffice Streaming');

serverSock = socket(AF_INET, SOCK_STREAM);
serverSock.bind(('',8000));
serverSock.listen(5);
Exemplo n.º 27
0
logfile.flush()
#================================================================
# initialise the plotly stream
#================================================================

# Get stream id from stream id list
stream_ids = tls.get_credentials_file()['stream_ids']
stream_id = stream_ids[0]

logfile.write(
    "brew_monitor.py: got the stream ids. About to start go.Stream...\n")
logfile.flush()

# Make instance of stream id object
stream_1 = go.Stream(
    token=stream_id,  # link stream id to 'token' key
    maxpoints=max_points  # keep a max of max_points pts on screen
)

logfile.write("brew_monitor.py: stream_1 object created.")
logfile.write("About to try an initialise the trace...\n")
logfile.flush()

# Initialize trace of streaming plot by embedding the unique stream_id
trace1 = go.Scatter(
    x=[],
    y=[],
    mode='lines+markers',
    stream=stream_1  # (!) embed stream id, 1 per trace
)

data = go.Data([trace1])
    def __init__(self, window_size=20):
        """
        INPUT:
            - window_size: how many data points to keep track of
        """
        # 2 stream id
        # api_cred.yml looks like this:
        # plotly:
        #     username: xxxx
        #     api_key: xxxx
        #     stream_ids:
        #         - xxxx
        #         - xxxx
        #         - xxxxx
        credentials = yaml.load(open(expanduser('tmp_cred.yml')))
        plotly.tools.set_credentials_file(**credentials['plotly']) # plotly credentials

        stream_ids = tls.get_credentials_file()['stream_ids']

        self.ids = {
            'line': stream_ids[0],
            'pie': stream_ids[1],
            'bar': stream_ids[2]
        }
        self.traces = {
            'line': {
                'stream_id': self.ids['line'],
                'trace': go.Scatter(
                    x=[],
                    y=[],
                    mode='lines+markers',
                    marker=dict(color="black"),
                    stream=go.Stream(token=self.ids['line'], maxpoints=80),
                    name='Average Score',
                    showlegend=False
                ),
                'title': 'Time Series',
                'filename': 'line-streaming'
            },
            'pie': {
                'stream_id': self.ids['pie'],
                'trace': go.Pie(
                    labels=['one','two','three'],
                    values=[20,50,100],
                    domain=dict(x=[0, 1]),
                    text=['one', 'two', 'three'],
                    stream=go.Stream(token=self.ids['pie'], maxpoints=80),
                    sort=False
                ),
                'title': 'Moving Pie',
                'filename': 'pie-streaming'
            },
            'bar': {
                'stream_id': self.ids['bar'],
                'trace': go.Bar(
                    x=[],
                    y=[],
                    # xaxis='x2',
                    # yaxis='y2',
                    marker=dict(color="green"),
                    name='Sentiment Score',
                    stream=go.Stream(token=self.ids['bar'], maxpoints=80),
                    showlegend=False
                ),
                'title': 'Moving Bar',
                'filename': 'bar-streaming'
            }
        }
        self.x = np.array([]) # list of x labels
        self.y = np.array([]) # list of y values
        self.y_mean = np.array([]) # list of y.mean()
        self.WIN_SIZE = window_size
        self.stream_line = None
        self.stream_bar = None
        self.chart_url = None

        self.init_interview_stream()
Exemplo n.º 29
0
    def __init__(self, plotqueue):
        print("initiating StreamingGraph")

        self.plotqueue = plotqueue

        # Make instance of stream id object
        self.stream_1 = go.Stream(
            token=self.stream_id,  # link stream id to 'token' key
            maxpoints=80  # keep a max of 80 pts on screen
        )
        print("stream 1 created")
        trace1 = go.Scatter(
            x=[],
            y=[],
            mode='lines+markers',
            stream=self.stream_1  # (!) embed stream id, 1 per trace
        )

        data = go.Data([trace1])

        # Add title to layout object
        layout = go.Layout(title='Time Series')
        print("layout created")

        # Make a figure object
        fig = go.Figure(data=data, layout=layout)

        # Send fig to Plotly, initialize streaming plot, open new tab
        py.iplot(fig, filename='python-streaming')

        # We will provide the stream link object the same token that's associated with the trace we wish to stream to
        self.s = py.Stream(self.stream_id)

        # We then open a connection
        self.s.open()

        # (*) Import module keep track and format current time
        import datetime
        import time

        i = 0  # a counter
        k = 5  # some shape parameter

        print("sleeping")
        # Delay start of stream by 5 sec (time to switch tabs)
        time.sleep(5)
        print("slept")

        self.plot_queue = Queue(maxsize=0)

        while True:
            if not self.plot_queue.empty():
                x, y = self.plotqueue.get()
                self.add_data(x, y)


##            # Current time on x-axis, random numbers on y-axis
##            x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
##            y = (np.cos(k*i/50.)*np.cos(i/50.)+np.random.randn(1))[0]
##
##            # Send data to your plot
##            self.s.write(dict(x=x, y=y))
##
##            #     Write numbers to stream to append current data on plot,
##            #     write lists to overwrite existing data on plot
##
##            time.sleep(1)  # plot a point every second

        self.s.close()