def init_plotly(): """ Prepares authenticate tokens for each trace, prepares layout and streams with corresponding scatter graph traces. :return: Returns initialized stream IDs for each trace """ logger = logging.getLogger(sys._getframe().f_code.co_name) # pull in Plotly authentication data plotly_creds = plotly.tools.get_credentials_file() username = plotly_creds['username'] api_key = plotly_creds['api_key'] token_cpu, token_temp, token_humidity, token_pressure, token_wu = plotly_creds['stream_ids'][0:5] plotly.plotly.sign_in(username, api_key) # create Stream structures with proper tokens and maximum preserved graph points my_stream_cpu = Stream(token=token_cpu, maxpoints=MAX_POINTS) my_stream_temp = Stream(token=token_temp, maxpoints=MAX_POINTS) my_stream_humidity = Stream(token=token_humidity, maxpoints=MAX_POINTS) my_stream_pressure = Stream(token=token_pressure, maxpoints=MAX_POINTS) my_stream_wu = Stream(token=token_wu, maxpoints=MAX_POINTS) # create Scatter-type structures with appropriate names; don't provide sample data as we'll provide it live in # Stream mode my_scatter_cpu = Scatter(x=[], y=[], stream=my_stream_cpu, name='CPU temperature', mode=TRACE_MODE) my_scatter_temp = Scatter(x=[], y=[], stream=my_stream_temp, name='Environment temperature', mode=TRACE_MODE) my_scatter_humidity = Scatter(x=[], y=[], stream=my_stream_humidity, name='Environment humidity', mode=TRACE_MODE) my_scatter_pressure = Scatter(x=[], y=[], stream=my_stream_pressure, name='Barometric pressure', yaxis='y2', mode=TRACE_MODE) my_scatter_wu = Scatter(x=[], y=[], stream=my_stream_wu, name='Outdoor temperature (Weather Underground)', mode=TRACE_MODE) # prepare Data structure my_data = Data([my_scatter_cpu, my_scatter_temp, my_scatter_humidity, my_scatter_pressure, my_scatter_wu]) # create Layout structure where we have one shared X axis (time series) and two Y axis, one left side (temperature # and humidity) and one right side (pressure) my_layout = Layout(title='Raspberry PI Sensors', xaxis=XAxis(title='Time'), yaxis=YAxis(title='Temperature [C] / Humidity [%]'), yaxis2=YAxis(title='Pressure [hPa]', overlaying='y', side='right', titlefont=Font(color='rgb(148, 103, 189)'), tickfont=Font(color='rgb(148, 103, 189)'))) # prepare Figure structure my_fig = Figure(data=my_data, layout=my_layout) try: # overwrite existing data on creating the new figure plotly.plotly.plot(my_fig, filename=PLOTLY_CHART_NAME, auto_open=False, fileopt=GRAPH_MODE) except requests.exceptions.ConnectionError, e: logger.error('Cannot connect to PlotLy to create chart: %s. Exiting...' % e) sys.exit(1)
def dataPlotlyHandler(): configuration = ConfigParser.ConfigParser() configuration.read('credentials.config') username = configuration.get('plotly', 'username') apikey = configuration.get('plotly', 'apikey') streamtokentx = configuration.get('plotly', 'streamtokentx') streamtokenrx = configuration.get('plotly', 'streamtokenrx') py.sign_in(username, apikey) trace_network_tx = Scatter(x=[], y=[], stream=Stream(token=streamtokentx, ), yaxis='tx') trace_network_rx = Scatter(x=[], y=[], stream=Stream(token=streamtokenrx, ), yaxis='rx') layout = Layout(title='IoT Lab Network Health System', yaxis=YAxis(title='Bytes'), yaxis2=YAxis(title='%', side='right', overlaying="y")) data = Data([trace_network_tx, trace_network_rx]) fig = Figure(data=data, layout=layout) print py.plot(fig, filename='IoT Lab Network Health System', auto_open=False) stream_network_tx = py.Stream(streamtokentx) stream_network_tx.open() stream_network_rx = py.Stream(streamtokenrx) stream_network_rx.open() counter = 0 while True: output = psutil.net_io_counters() randoma = randint(0, 1000) randomb = randint(0, 1000) stream_network_tx.write({'x': counter, 'y': randoma}) stream_network_rx.write({'x': counter, 'y': randomb}) counter += 1 time.sleep(0.25) stream_network_tx.close() stream_network_rx.close()
def setup(self): my_creds = tls.get_credentials_file() # read credentials py.sign_in(my_creds['username'], my_creds['api_key']) # (New syntax!) Plotly sign in tls.embed('streaming-demos', '6') my_stream_ids = tls.get_credentials_file()['stream_ids'] # Get stream id from stream id list self.my_stream_id = my_stream_ids[0] # Make instance of stream id object my_stream = Stream( token=self.my_stream_id, # N.B. link stream id to 'token' key maxpoints=200) # N.B. keep a max of 80 pts on screen # Initialize trace of streaming plot by embedding the unique stream_id my_data = Data( [Scatter(x=[], y=[], mode='lines+markers', stream=my_stream)]) # embed stream id, 1 per trace # Add title to layout object my_layout = Layout(title='Quake monitor') # Make instance of figure object my_fig = Figure(data=my_data, layout=my_layout) # Initialize streaming plot, open new tab unique_url = py.plot(my_fig, filename='qm_first-stream')
def test_initialize_stream_plot(): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, filename='stream-test') assert url == 'https://plot.ly/~PythonAPI/461' time.sleep(.5)
def make_plot(): tls.set_credentials_file(stream_ids=[my_stream_id]) my_stream = Stream(token=my_stream_id, maxpoints=100) my_data = Data([Scatter(x=[], y=[], mode="lines+markers", stream=my_stream)]) my_layout = Layout(title="Time Series") my_fig = Figure(data=my_data, layout=my_layout) unique_url = py.plot(my_fig, filename="demo_smap_streaming")
def graph(self): trace_network_tx = Scatter(x=[], y=[], stream=Stream(token=self.streamtokentx, ), yaxis='tx') trace_network_rx = Scatter(x=[], y=[], stream=Stream(token=self.streamtokenrx, ), yaxis='rx') layout = Layout(title='IoTPy Network Health System', yaxis=YAxis(title='Bytes'), yaxis2=YAxis(title='%', side='right', overlaying="y")) data = Data([trace_network_tx, trace_network_rx]) fig = Figure(data=data, layout=layout) print py.plot(fig, filename='IoTPy Network Health System', auto_open=False) stream_network_tx = py.Stream(self.streamtokentx) stream_network_tx.open() stream_network_rx = py.Stream(self.streamtokenrx) stream_network_rx.open() time.sleep(5) counter = 0 while True: output = psutil.net_io_counters() print "Network Bytes Tx %s" % output.bytes_sent print "Network Bytes Rx %s" % output.bytes_recv stream_network_tx.write({'x': counter, 'y': output.bytes_sent}) stream_network_rx.write({'x': counter, 'y': output.bytes_recv}) counter += 1 time.sleep(0.25) stream_network_tx.close() stream_network_rx.close()
def test_initialize_stream_plot(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot( [Scatter(x=[], y=[], mode="markers", stream=stream)], auto_open=False, world_readable=True, filename="stream-test2", ) self.assertTrue(url.startswith("https://plot.ly/~PythonAPI/")) time.sleep(0.5)
def test_stream_multiple_points(): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, filename='stream-test') time.sleep(.5) my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=[1, 2, 3, 4], y=[2, 1, 2, 5])) time.sleep(.5) my_stream.close()
def test_stream_single_points(): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) res = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, filename='stream-test') time.sleep(.5) my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=1, y=10)) time.sleep(.5) my_stream.close()
def test_stream_multiple_points(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot( [Scatter(x=[], y=[], mode="markers", stream=stream)], auto_open=False, world_readable=True, filename="stream-test2", ) time.sleep(0.5) my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=[1, 2, 3, 4], y=[2, 1, 2, 5])) time.sleep(0.5) my_stream.close()
def test_stream_layout(): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)], auto_open=False, filename='stream-test') time.sleep(.5) title_0 = "some title i picked first" title_1 = "this other title i picked second" my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=1, y=10), layout=Layout(title=title_0)) time.sleep(.5) my_stream.close() my_stream.open() my_stream.write(Scatter(x=1, y=10), layout=Layout(title=title_1)) my_stream.close()
def test_stream_layout(self): py.sign_in(un, ak) stream = Stream(token=tk, maxpoints=50) url = py.plot( [Scatter(x=[], y=[], mode="markers", stream=stream)], auto_open=False, world_readable=True, filename="stream-test2", ) time.sleep(0.5) title_0 = "some title i picked first" title_1 = "this other title i picked second" my_stream = py.Stream(tk) my_stream.open() my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_0)) time.sleep(0.5) my_stream.close() my_stream.open() my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_1)) my_stream.close()
STREAMING_PERIOD = 5 if __name__ == "__main__": print(("Streaming to Plotly each {0} seconds.".format(STREAMING_PERIOD))) stream = None try: radiationWatch = RadiationWatch(24, 23).setup() py.sign_in(USERNAME, API_KEY) url = py.plot(Figure(layout=Layout(title=PLOT_TITLE, xaxis=dict(title='Timestamp'), yaxis=dict(title='Dose (uSv/h)')), data=Data([ Scatter(x=[], y=[], mode='lines', stream=Stream(token=STREAMING_TOKEN)) ])), filename=PLOT_TITLE) print(("Plotly graph URL: {0}".format(url))) stream = py.Stream(STREAMING_TOKEN) stream.open() while 1: readings = radiationWatch.status() x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') print(("Streaming... {0}.".format([x, readings['uSvh']]))) stream.write(dict(x=x, y=readings['uSvh'])) time.sleep(STREAMING_PERIOD) except Exception as e: print(e) finally: radiationWatch.close()
@homepage GitHub: https://github.com/JohannesFriedrich ''' import plotly.plotly as py from plotly.graph_objs import Stream, Scatter, Data, Layout, Figure # auto sign-in with credentials or use py.sign_in() from HIMUServer import HIMUServer myHIMUServer = HIMUServer() maxpoints = 200 stream1 = Stream( token='your_token_1', # (!) link stream id to 'token' key maxpoints=maxpoints ) stream2 = Stream( token='your_token_2', # (!) link stream id to 'token' key maxpoints=maxpoints ) stream3 = Stream( token='your_token_3', # (!) link stream id to 'token' key maxpoints=maxpoints ) trace1 = Scatter( x=[],
from plotly.graph_objs import Scatter, Layout, Figure, Data, Stream, YAxis # plotly graph objects import time # timer functions import serial import datetime username = '******' api_key = 'k53c99f7d1' stream_token_lightlevel = 'doxcsw1igt' stream_token_voltage = 'vlx5vddak3' stream_token_temperature = 'iuqh3xt5ph' py.sign_in('zaneshaq', 'k53c99f7d1') trace_lightlevel = Scatter(x=[], y=[], stream=Stream(token=stream_token_lightlevel, maxpoints=200), yaxis='y') trace_voltage = Scatter(x=[], y=[], stream=Stream(token=stream_token_voltage, maxpoints=200), yaxis='y2') trace_temperature = Scatter(x=[], y=[], stream=Stream(token=stream_token_temperature, maxpoints=200), yaxis='y3') layout = Layout(title='Zane Imran Sun Tracker Project - Brightsparks',
def plotTemplate(start_x, start_y, length, width): ''' Plots the data on the Plotly Framework. ''' global scatter_write_stream, end_write_stream py.sign_in(plotly_username, plotly_api_key) tls.set_credentials_file(username=plotly_username, api_key=plotly_api_key) tls.set_credentials_file(stream_ids=plotly_streaming_keys) stream_ids = tls.get_credentials_file()['stream_ids'] scatter_stream_id = stream_ids[0] scatter_data_stream = Stream( token=scatter_stream_id # (!) link stream id to 'token' key ) end_stream_id = stream_ids[1] end_data_stream = Stream( token=end_stream_id # (!) link stream id to 'token' key ) # Prepares the layout of the axis layout = Layout( showlegend=True, autosize=True, height=800, width=800, title="MAP", xaxis=XAxis( zerolinewidth=4, gridwidth=1, showgrid=True, zerolinecolor="#969696", gridcolor="#bdbdbd", linecolor="#636363", mirror=True, zeroline=False, showline=True, linewidth=6, type="linear", range=[0, length], autorange=False, autotick=False, dtick=15, tickangle=-45, title="X co-ordinate" ), yaxis=YAxis( zerolinewidth=4, gridwidth=1, showgrid=True, zerolinecolor="#969696", gridcolor="#bdbdbd", linecolor="#636363", mirror=True, zeroline=False, showline=True, linewidth=6, type="linear", range=[width, 0], autorange=False, autotick=False, dtick=15, tickangle=-45, title="Y co-ordinate" ) ) # Prepares the startPoint plot startData = Scatter( x=[start_x], y=[start_y], mode='markers', marker=Marker(color="red", size="10", symbol="triangle-left"), showlegend=False, name=mac, text=["Start point"], legendgroup=mac, ) # Prepares the endPoint plot endData = Scatter( x=[], y=[], mode='markers', marker=Marker(color="red", size="10"), showlegend=False, name=mac, text=["End point"], legendgroup=mac, stream=end_data_stream ) # Prepares the scatter data plot scatter_data = Scatter( x=[], y=[], mode='lines + text', text=[], name=mac, marker=Marker(color="red"), opacity="0.5", legendgroup=mac, stream=scatter_data_stream ) data = Data([scatter_data, startData, endData]) fig = Figure(data=data, layout=layout) py.plot(fig, filename='Sample Code For History Of Clients ') # Sets the stream to the specific scatters scatter_write_stream = py.Stream(scatter_stream_id) end_write_stream = py.Stream(end_stream_id)
def plot_graph(): py.plot( Data([ Scatter(x=[], y=[], stream=Stream(token=stream_id, maxpoints=100)) ]))
############################################################### ##################### Sets up plotly details ################## username = '******' api_key = 'k53c99f7d1' stream_token_temperature = 'iuqh3xt5ph' stream_token_lightlevel = 'vlx5vddak3' py.sign_in('zaneshaq', 'k53c99f7d1') # JSON code for plotly graph trace_temperature = Scatter( x=[], y=[], name='Temp', stream=Stream(token=stream_token_temperature # Sets up temperature stream ), yaxis='y') trace_lightlevel = Scatter( x=[], y=[], name='Light %', stream=Stream(token=stream_token_lightlevel # Sets up Lightlevel stream ), yaxis='y2') layout = Layout( title='Sun Tracker - Temperature and Lightlevel Readings', #Labels graph yaxis=YAxis(title='Celcius'), yaxis2=YAxis(title='Light %', side='right', overlaying="y"))
#!/usr/bin/env python import plotly.plotly as py import plotly.tools as tls from plotly.graph_objs import Stream, Data, Figure, Scatter, Layout stream_id = tls.get_credentials_file()['stream_ids'][1] stream = Stream(token=stream_id, maxpoints=50) trace = Scatter(x=[], y=[], mode='lines+markers', stream=stream) data = Data([trace]) layout = Layout(title='Streaming test') figure = Figure(data=data, layout=layout) unique_url = py.plot(figure, filename='stream_test', auto_open=False) print('Plot URL: {0}'.format(unique_url))
# Get all tables from device tables = device.list_tables() # Get Streaming Tokens from plot.ly stream_ids = tls.get_credentials_file()['stream_ids'] # Grab first Token in list stream_id = stream_ids[0] # Used to check if header should be used has_ran = False # File descriptor for log file log_file = os.open("logfile.txt", os.O_RDWR | os.O_APPEND | os.O_CREAT) # Set up our traces turbidity = Scatter(x=[], y=[], mode='lines+markers', stream=Stream(token=stream_id, maxpoints=80), name="Ana 1 (NTU)") turbidity2 = Scatter(x=[], y=[], mode='lines+markers', stream=Stream(token=stream_ids[1], maxpoints=80), name="Ana 2 (NTU)") turbidity3 = Scatter(x=[], y=[], mode='lines+markers', stream=Stream(token=stream_ids[2], maxpoints=80), name="AquiTurbo (NTU)") temperature = Scatter(x=[],
mirror=True, zeroline=False, showline=True, linewidth=6, type="linear", range=[data_dict["width"], 0], autorange=False, autotick=False, dtick=15, tickangle=-45, title="Y co-ordinate")) tls.set_credentials_file(stream_ids=["kk9r8fbr07", "5iv4ntu3x1"]) stream_ids = tls.get_credentials_file()['stream_ids'] stream_id = stream_ids[0] stream = Stream(token=stream_id # (!) link stream id to 'token' key ) processed_data = Scatter(x=[], y=[], mode='lines + text', text=[], name=mac, marker=Marker(color="red"), opacity="0.5", legendgroup=mac, stream=stream) data = Data([processed_data]) fig = Figure(data=data, layout=layout) plot_url = py.plot(fig, filename='Demo') writeStream = py.Stream(stream_id)
from plotly.graph_objs import Legend, Font, Stream, Scatter, Layout, Data, Figure, XAxis, YAxis import csv import plotly.plotly as py import plotly.tools as tls import numpy as np import time # Get Streaming Tokens from plot.ly stream_ids = tls.get_credentials_file()['stream_ids'] # Grab first Token in list stream_id = stream_ids[0] # Create the stream stream_obj = Stream(token=stream_id, maxpoints=80) # Set up our plot's traces turbidity = Scatter(x=[], y=[], mode='lines+markers', stream=stream_obj, name="Turbidity (NTU)") turbidity2 = Scatter(x=[], y=[], mode='lines+markers', stream=Stream(token=stream_ids[1], maxpoints=80), name="Turbidity Sensor 2 (NTU)") # Set up data sets data = Data([turbidity, turbidity2]) # Configure the Layout