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_credentials_tools(): original_creds = tls.get_credentials_file() expected = ['username', 'stream_ids', 'api_key'] assert all(x in original_creds for x in expected) # now, if that worked, we can try this! tls.reset_credentials_file() reset_creds = tls.get_credentials_file() tls.set_credentials_file(**original_creds) assert all(x in reset_creds for x in expected) creds = tls.get_credentials_file() assert all(x in creds for x in expected) assert original_creds == creds
def main(): try: credentials = tls.get_credentials_file() except: ## except credentials error and print for them to enter something credentials = {} credentials['username'] = raw_input("Plotly Username: "******"api key: ") ### get password py.sign_in(credentials['username'], credentials['api_key']) survey_file = "survey.csv" run_data = d.main() for runner in run_data.runners: runner.make_data() print runner.median #print runner.num , runner.total , runner.count, runner.avg, runner.dur, runner.mpd, runner.rpd INDEX = completeSurvey() #SD is a SurveyData object, has all of the respondents SD = read_survey(survey_file, run_data, INDEX) mydict = SD.makeDictionary() SD.groupSocial() SD.groupStarter() SD.groupQ1() SD.groupQ2() #list of runners that did not respond nonResponders = sort(run_data, SD) #list of runners that did respond surveyResponders = SD.responses plotQ1(SD) #plotQ2(SD) #starters(SD) plotSocial(SD)
def __init__(self): ChimeraCLI.__init__(self, "MoniT", "Monitor telescope temperature", 0.0, port=9010) ''' Make intra/extra focal observations in a grid of alt/az. ''' self.addHelpGroup("RUN", "Start/Stop/Info") self.addHelpGroup("TELESCOPE", "Telescope") self.addInstrument(name="telescope", cls="Telescope", required=True, help="Telescope instrument to be used. If blank, try to guess from chimera.config", helpGroup="TELESCOPE") self.addParameters(dict(name="utime", long="updatetime", type=float, help="How long it will wait before reading in new data (in seconds).", default=30., metavar="utime")) self.addParameters(dict(name="maxpoints", long="maxpoints", type=int, help="Maximum number of points to plot. Set to -1 for unlimited.", default=-1, metavar="maxpoints")) self.stream_ids = tls.get_credentials_file()['stream_ids'] self._ns = 4 # number of sensors self._sindex = [2, 4, 6, 8] # sensor index self.streams = [None, None, None, None] self.traces = [None, None, None, None] self.tlabels = ['M1 Temperature', 'M2 Temperature', 'Front Rod', 'Tube Rod'] if len(self.stream_ids) < 4: raise IOError( 'At least 4 PlotLy tokens are required to stream the data. Add them to your credentials, see https://plot.ly/python/streaming-tutorial/')
def __init__(self): tls.set_credentials_file(stream_ids=["67ldjwqppe", "hyinh0zrb1", \ "t4tqyzk86o", "66qg05p8s9", "zbl5fi5amr"]) stream_ids = tls.get_credentials_file()['stream_ids'] streams = [] traces = [] for i in range(4): streams.append(Stream(token=stream_ids[i], maxpoints = 100)) traces.append(Scatter(x=[], y=[], mode='lines+markers', \ stream=streams[i])) layout = Layout(title='PeaceLily') data = Data(traces) fig = Figure(data=data, layout=layout) unique_uql = py.plot(fig, filename='PeaceLilly') self.active_streams = [] for i in range(4): self.active_streams.append(py.Stream(stream_ids[i])) self.active_streams[-1].open()
def get_credentials(): """Returns the credentials that will be sent to plotly.""" credentials = tools.get_credentials_file() for credentials_key in credentials: if _credentials.get(credentials_key): credentials[credentials_key] = _credentials[credentials_key] return credentials
def test_get_credentials_file(self): # Check get_credentials returns all the keys original_creds = tools.get_credentials_file() expected = ['username', 'stream_ids', 'api_key', 'proxy_username', 'proxy_password'] self.assertTrue(all(x in original_creds for x in expected))
def get_credentials(): """ Returns a copy of the user supplied credentials. """ global _credentials if ('username' in _credentials) and ('api_key' in _credentials): return copy.copy(_credentials) else: return tools.get_credentials_file()
def test_get_credentials(self): session_credentials = session.get_session_credentials() if 'username' in session_credentials: del session._session['credentials']['username'] if 'api_key' in session_credentials: del session._session['credentials']['api_key'] creds = py.get_credentials() file_creds = tls.get_credentials_file() self.assertEqual(creds, file_creds)
def test_get_credentials(): if 'username' in py._credentials: del py._credentials['username'] if 'api_key' in py._credentials: del py._credentials['api_key'] creds = py.get_credentials() file_creds = tls.get_credentials_file() print(creds) print(file_creds) assert creds == file_creds
def _get_session_username_and_key(): file_credentials = tools.get_credentials_file() if ('username' in _credentials) and ('api_key' in _credentials): username, api_key = _credentials['username'], _credentials['api_key'] elif ('username' in file_credentials) and ('api_key' in file_credentials): (username, api_key) = (file_credentials['username'], file_credentials['api_key']) else: raise exceptions.PlotlyLocalCredentialsError() return username, api_key
def get_credentials(): """Returns the credentials that will be sent to plotly.""" credentials = tools.get_credentials_file() session_credentials = get_session_credentials() for credentials_key in credentials: # checking for not false, but truthy value here is the desired behavior session_value = session_credentials.get(credentials_key) if session_value is False or session_value: credentials[credentials_key] = session_value return credentials
def test_get_credentials(): session_credentials = session.get_session_credentials() if 'username' in session_credentials: del session._session['credentials']['username'] if 'api_key' in session_credentials: del session._session['credentials']['api_key'] creds = py.get_credentials() file_creds = tls.get_credentials_file() print(creds) print(file_creds) assert creds == file_creds
def initGraph(): global shareName global stream strm_ids = tls.get_credentials_file()['stream_ids'] strm = Stream(token=strm_ids[0],maxpoints=100) trace1 = Scatter(x=[], y=[], mode='lines+markers', strm = strm) data = Data([trace1]) layout = Layout(title='Live Stock Price(' + shareName + ")") fig = Figure(data=data, layout=layout) unique_url = py.plot(fig, filename='s7_first-stream') stream = py.Stream(strm_ids[0]) stream.open() print "[Notice] | Graph Stream Initilization Complete."
def main(): interval = 60 #Frequency of data collection [s] plot_window = 86400 #Length of time to plot [s] points = plot_window/interval #Send to 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 = 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 = Scatter( x=[], y=[], mode='lines+markers', stream=stream # (!) embed stream id, 1 per trace ) data = Data([trace1]) # Add title to layout object layout = Layout(title='Bedroom Temperature') # Make a figure object fig = Figure(data=data, layout=layout) # (@) Send fig to Plotly, initialize streaming plot, open new tab unique_url = py.plot(fig, filename='Bedroom Temperature') # (@) Make instance of the Stream link object, # with same stream id as Stream id object s=py.Stream(stream_id) # (@) Open the stream s.open() while True: x=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') y=sensor.read_temperature() s.write(dict(x=x, y=y)) time.sleep(interval) s.close()
def build_streams(): global STREAMS, STREAMS_BY_ID stream_ids = tls.get_credentials_file()['stream_ids'] for i, stream_id in enumerate(stream_ids): if stream_id in STREAMS_BY_ID: s = STREAMS_BY_ID[stream_id] if s.index != i: if s.index in STREAMS: del STREAMS[s.index] s.index = i STREAMS[i] = s continue s = Stream(id=stream_id, index=i) STREAMS[i] = s STREAMS_BY_ID[s.id] = s
def _validation_key_logic(): creds_on_file = tools.get_credentials_file() if 'username' in _credentials: username = _credentials['username'] elif 'username' in creds_on_file: username = creds_on_file['username'] else: username = None if 'api_key' in _credentials: api_key = _credentials['api_key'] elif 'api_key' in creds_on_file: api_key = creds_on_file['api_key'] else: api_key = None if username is None or api_key is None: raise exceptions.PlotlyLocalCredentialsError() return (username, api_key)
def main(): try: credentials = tls.get_credentials_file() except: ## except credentials error and print for them to enter something credentials = {} credentials['username'] = raw_input("Plotly Username: "******"api key: ") ### get password try: py.sign_in(credentials['username'], credentials['api_key']) print "let's read some data" #data object t = Data(False, True) #read from file t.read_data('submissions.csv') return t except: print "was not able to sign into plotly"
def start(self): for subscriber in self.subscribers: for metric_buffer in subscriber.metric_buffers.values(): _LOGGER.info('Subscribing to %s' % metric_buffer.name) local_stream_ids = tls.get_credentials_file()['stream_ids'] if len(local_stream_ids) < metric_buffer.num_channels: raise ValueError( "Not enough stream tokens. Required: %s. Actual: %s. " "Add a stream token to 'stream_ids' in your " "~/.plotly/.credentials file. More details " "at https://plot.ly/python/getting-started/" % (metric_buffer.num_channels, len(local_stream_ids))) self.setup_metric_streams(local_stream_ids, metric_buffer.name, metric_buffer.num_channels) callback = self._callback_factory(metric_buffer.num_channels) subscriber.subscribe(metric_buffer.name, callback)
def _send_to_plotly(figure, **plot_options): """ """ fig = tools._replace_newline(figure) # does not mutate figure data = json.dumps(fig['data'] if 'data' in fig else [], cls=utils._plotlyJSONEncoder) file_credentials = tools.get_credentials_file() if ('username' in _credentials) and ('api_key' in _credentials): username, api_key = _credentials['username'], _credentials['api_key'] elif ('username' in file_credentials) and ('api_key' in file_credentials): (username, api_key) = (file_credentials['username'], file_credentials['api_key']) else: raise exceptions.PlotlyLocalCredentialsError() kwargs = json.dumps(dict(filename=plot_options['filename'], fileopt=plot_options['fileopt'], world_readable=plot_options['world_readable'], layout=fig['layout'] if 'layout' in fig else {}), cls=utils._plotlyJSONEncoder) payload = dict(platform='python', # TODO: It'd be cool to expose the platform for RaspPi and others version=version.__version__, args=data, un=username, key=api_key, origin='plot', kwargs=kwargs) url = tools.get_config_file()['plotly_domain'] + "/clientresp" r = requests.post(url, data=payload) r.raise_for_status() r = json.loads(r.text) if 'error' in r and r['error'] != '': print((r['error'])) if 'warning' in r and r['warning'] != '': warnings.warn(r['warning']) if 'message' in r and r['message'] != '': print((r['message'])) return r
def main(): # Send to 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 = Stream( token=stream_id, maxpoints=80 # (!) link stream id to 'token' key # (!) keep a max of 80 pts on screen ) # Initialize trace of streaming plot by embedding the unique stream_id trace1 = Scatter(x=[], y=[], mode="lines+markers", stream=stream) # (!) embed stream id, 1 per trace data = Data([trace1]) # Add title to layout object layout = Layout(title="Bedroom Temperature") # Make a figure object fig = Figure(data=data, layout=layout) # (@) Send fig to Plotly, initialize streaming plot, open new tab unique_url = py.plot(fig, filename="s7_first-stream") # (@) Make instance of the Stream link object, # with same stream id as Stream id object s = py.Stream(stream_id) # (@) Open the stream s.open() i = 0 k = 5 N = 200 while True: x = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") y = sensor.read_temperature() s.write(dict(x=x, y=y)) time.sleep(5) s.close()
def setup(self): #check file f = self.check_file() #if success checking file if f == 0: print 'ler ficheiro autenticacao' my_cred = tls.get_credentials_file() print my_cred if (my_cred['username'] != '' ) and (my_cred['api_key'] != '') : print 'inicio de autenticacao' t=py.sign_in(my_cred['username'], my_cred['api_key']) print 'resultado autenticaco: '+ str(t) if t is None: print 'autenticacao concluida com sucesso' return 0 else: print '!!! ERRO de autenticacao' return -1 else: print '!!! ERRO a ler ficheiro de autenticacao plotly - pelo menos um dos campos esta vazio' return -1
def init_progress_plot(): stream_ids = tls.get_credentials_file()['stream_ids'] unseen_pts = np.asarray([m['pt'] for m in mapping if 'seen' not in m]) x, y = unseen_pts[:,0], unseen_pts[:,1] unseen_trace = Scatter(x=x, y=y, mode='markers', stream=Stream(token=stream_ids[0])) seen_pts = np.asarray([m['pt'] for m in mapping if 'seen' in m]) x, y = (seen_pts[:,0], seen_pts[:,1]) if len(seen_pts) else ([], []) seen_trace = Scatter(x=x, y=y, mode='markers', stream=Stream(token=stream_ids[1])) data = Data([unseen_trace, seen_trace]) layout = Layout(width=600, height=600) plot = py.plot(Figure(data=data, layout=layout), filename='erato-traversal-progress') stream = {'unseen': py.Stream(stream_ids[0]), 'seen': py.Stream(stream_ids[1])} for v in stream.values(): v.open() return stream
# -*- mode: python; coding: utf-8 -*- # Copyright (C) 2014, Oscar Acena <*****@*****.**> # This software is under the terms of Apache License v2 or later. from __future__ import print_function, division # (*) To communicate with Plotly's server, sign in with credentials file import plotly.plotly as py # (*) Useful Python/Plotly tools import plotly.tools as tls # (*) Graph objects to piece together plots from plotly.graph_objs import * 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 = Stream( token=stream_id, # (!) 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 trace1 = Scatter( x=[], y=[], mode='lines+markers',
def getStreamID(): return tls.get_credentials_file()['stream_ids']
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
def initialize(self): py.sign_in(self.username, self.password) self.stream_ids = tls.get_credentials_file()['stream_ids']
def __init__(self): #authenticate using settings tls.set_credentials_file(username=settings.PLOTLY_USER, api_key=settings.PLOTLY_API) tls.set_credentials_file(stream_ids=settings.PLOTLY_STREAMS) self.credentials = 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 = Stream( # token=stream_id, # (!) link stream id to 'token' key # maxpoints=80 # (!) keep a max of 80 pts on screen #) # Init. 1st scatter obj (the pendulums) with stream_ids[1] self.prices = Scatter( x=[], # init. data lists y=[], mode='lines+markers', # markers at pendulum's nodes, lines in-bt. # reduce opacity marker=Marker(size=1), # increase marker size stream=Stream(token=self.credentials[0], maxpoints=2000) # (!) link stream id to token ) # Set limits and mean, but later self.limit_up = Scatter( x=[], # init. data lists y=[], mode='lines', # path drawn as line line=Line(color='rgba(31,119,180,0.15)'), # light blue line color stream=Stream( token=self.credentials[1], maxpoints=2000 # plot a max of 100 pts on screen )) self.limit_dwn = Scatter( x=[], # init. data lists y=[], mode='lines', # path drawn as line line=Line(color='rgba(31,119,180,0.15)'), # light blue line color stream=Stream( token=self.credentials[2], maxpoints=2000 # plot a max of 100 pts on screen )) self.ranging = Scatter( x=[], # init. data lists y=[], mode='markers', line=Line(color='rgba(200,0,0,0.5)' ), # red if the system thinks it ranges # reduce opacity marker=Marker(size=5), # increase marker size stream=Stream(token=self.credentials[3], maxpoints=1000)) self.fills_buy = Scatter( x=[], # init. data lists y=[], mode='markers', marker=Marker( size=15, color='rgba(76,178,127,0.7)'), # increase marker size stream=Stream(token=self.credentials[4], maxpoints=10)) self.fills_sell = Scatter( x=[], # init. data lists y=[], mode='markers', marker=Marker(size=15, color='rgba(178,76,76,0.7)'), # increase marker size stream=Stream(token=self.credentials[5], maxpoints=10)) # (@) Send fig to Plotly, initialize streaming plot, open tab self.stream1 = py.Stream(self.credentials[0]) # (@) Make 2nd instance of the stream link object, # with same stream id as the 2nd stream id object (in trace2) self.stream2 = py.Stream(self.credentials[1]) self.stream3 = py.Stream(self.credentials[2]) self.stream4 = py.Stream(self.credentials[3]) self.stream5 = py.Stream(self.credentials[4]) self.stream6 = py.Stream(self.credentials[5]) # data self.data = Data([ self.prices, self.limit_up, self.limit_dwn, self.ranging, self.fills_buy, self.fills_sell ]) # Make figure object self.layout = Layout(showlegend=False) self.fig = Figure(data=self.data, layout=self.layout) self.unique_url = py.plot(self.fig, filename='Azure-IB Monitor', auto_open=False) # (@) Open both streams self.stream1.open() self.stream2.open() self.stream3.open() self.stream4.open() self.stream5.open() self.stream6.open() print "streams initaited"
#--------------------------------------- import plotly.tools as tls tls.set_credentials_file(username="******", api_key="bdeNJOC2IQfL6oB6CppV") # to get your credentials credentials = tls.get_credentials_file() import csv import plotly.plotly as py import plotly.graph_objs as go #---------------------------------------------------------------------- import os def plot_temp(csv_path): """ http://census.ire.org/data/bulkdata.html """ counties = {} county = [] pop = [] counter = 0 with open(csv_path) as csv_handler: reader = csv.reader(csv_handler) for row in reader: print row if counter == 0: counter += 1 continue
import plotly.tools as tls username = '******' api_key = 'w6sZmOJN7WpEg767Cz5V' stream_ids = ["7f1r9f7kwx", "hlhsuj7pyu"] mapbox_access_tokens = [ "pk.eyJ1IjoibS1pb3QtdHJhbnNhY3Rpb25zIiwiYSI6ImNqYTJqNjZuaDh5eGcycXFzeDlwMDhsZG8ifQ.sBCXyy-RYSnznknB1QikVg", "pk.eyJ1IjoibS1pb3QtdHJhbnNhY3Rpb25zIiwiYSI6ImNqYTJqM3IwMTV6ejgycG12anJzdG52dTYifQ.jLeHCjv9EqR80ctlVRYHTg" ] tls.set_credentials_file(username=username, api_key=api_key, stream_ids=stream_ids) stream_tokens = tls.get_credentials_file()['stream_ids']
table = db['dmv'] #initialize vars #TODO: get rid of these. branch names from branch_data.json, limit targets by geo. la_branches = [502, 617, 508, 652, 510, 511, 576] #branch_names = {'502':"Los Angeles", '617':"Lincoln Park", '508':"Hollywood", '652':"West Hollywood", '510':"Glendale", '511':"Montebello", '576':"Bell Gardens"} dmvUrl = 'http://apps.dmv.ca.gov/fodata/Output2.txt' f = open('branch_data.json'); full_offices = json.loads(f.read()); f.close(); traces = [] inited = [] credentials = tls.get_credentials_file() class Trace(): def __init__(self, id, name): self.name = name self.id = id self.apptValue = [] self.noApptValue = [] self.update = [] def updateWait(self, apptValue, noApptValue, update): self.apptValue.append(apptValue) self.noApptValue.append(noApptValue) self.update.append(update) def getName(self):
def __init__(self): #authenticate using settings tls.set_credentials_file(username=settings.PLOTLY_USER, api_key=settings.PLOTLY_API) tls.set_credentials_file(stream_ids=settings.PLOTLY_STREAMS) self.credentials = 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 = Stream( # token=stream_id, # (!) link stream id to 'token' key # maxpoints=80 # (!) keep a max of 80 pts on screen #) # Init. 1st scatter obj (the pendulums) with stream_ids[1] self.prices = Scatter( x=[], # init. data lists y=[], mode='lines+markers', # markers at pendulum's nodes, lines in-bt. # reduce opacity marker=Marker(size=1), # increase marker size stream=Stream(token=self.credentials[0], maxpoints=2000) # (!) link stream id to token ) # Set limits and mean, but later self.limit_up = Scatter( x=[], # init. data lists y=[], mode='lines', # path drawn as line line=Line(color='rgba(31,119,180,0.15)'), # light blue line color stream=Stream( token=self.credentials[1], maxpoints=2000 # plot a max of 100 pts on screen ) ) self.limit_dwn = Scatter( x=[], # init. data lists y=[], mode='lines', # path drawn as line line=Line(color='rgba(31,119,180,0.15)'), # light blue line color stream=Stream( token=self.credentials[2], maxpoints=2000# plot a max of 100 pts on screen ) ) self.ranging = Scatter( x=[], # init. data lists y=[], mode='markers', line=Line(color='rgba(200,0,0,0.5)'), # red if the system thinks it ranges # reduce opacity marker=Marker(size=5), # increase marker size stream=Stream(token=self.credentials[3], maxpoints=1000) ) self.fills_buy = Scatter( x=[], # init. data lists y=[], mode='markers', marker=Marker(size=15, color='rgba(76,178,127,0.7)'), # increase marker size stream=Stream(token=self.credentials[4], maxpoints=10) ) self.fills_sell = Scatter( x=[], # init. data lists y=[], mode='markers', marker=Marker(size=15, color='rgba(178,76,76,0.7)'), # increase marker size stream=Stream(token=self.credentials[5], maxpoints=10) ) # (@) Send fig to Plotly, initialize streaming plot, open tab self.stream1 = py.Stream(self.credentials[0]) # (@) Make 2nd instance of the stream link object, # with same stream id as the 2nd stream id object (in trace2) self.stream2 = py.Stream(self.credentials[1]) self.stream3 = py.Stream(self.credentials[2]) self.stream4 = py.Stream(self.credentials[3]) self.stream5 = py.Stream(self.credentials[4]) self.stream6 = py.Stream(self.credentials[5]) # data self.data = Data([self.prices,self.limit_up,self.limit_dwn,self.ranging, self.fills_buy, self.fills_sell]) # Make figure object self.layout = Layout(showlegend=False) self.fig = Figure(data=self.data, layout=self.layout) self.unique_url = py.plot(self.fig, filename='Azure-IB Monitor', auto_open=False) # (@) Open both streams self.stream1.open() self.stream2.open() self.stream3.open() self.stream4.open() self.stream5.open() self.stream6.open() print "streams initaited"
def get_plot(filename=None): stream_tokens = plotly_tools.get_credentials_file()['stream_ids'] token_1 = stream_tokens[0] token_2 = stream_tokens[1] token_3 = stream_tokens[2] stream_id1 = dict(token=token_1, maxpoints=1500) stream_id2 = dict(token=token_2, maxpoints=1500) stream_id3 = dict(token=token_3, maxpoints=1500) # Get existing data x_data = { 'time': [], } y_data = { 'temp': [], 'cloudiness': [], 'rain': [], } if filename is not None: data = pandas.read_csv(filename, names=names) data.date = pandas.to_datetime(data.date) # Convert from UTC data.date = data.date + datetime.timedelta(hours=11) x_data['time'] = data.date y_data['temp'] = data.ambient_temp_C y_data['cloudiness'] = data.sky_temp_C y_data['rain'] = data.rain_frequency trace1 = plotly_go.Scatter( x=x_data['time'], y=y_data['temp'], name='Temperature', mode='lines', stream=stream_id1) trace2 = plotly_go.Scatter( x=x_data['time'], y=y_data['cloudiness'], name='Cloudiness', mode='lines', stream=stream_id2) trace3 = plotly_go.Scatter( x=x_data['time'], y=y_data['rain'], name='Rain', mode='lines', stream=stream_id3) fig = plotly_tools.make_subplots(rows=3, cols=1, shared_xaxes=True, shared_yaxes=False) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 2, 1) fig.append_trace(trace3, 3, 1) fig['layout'].update(title="MQ Observatory Weather") fig['layout']['xaxis1'].update(title="Time [AEDT]") fig['layout']['yaxis1'].update(title="Temp [C]") fig['layout']['yaxis2'].update(title="Cloudiness") fig['layout']['yaxis3'].update(title="Rain Sensor") url = plotly.plot(fig, filename='MQObs Weather - Temp') print("Plot available at {}".format(url)) stream_temp = plotly.Stream(stream_id=token_1) stream_temp.open() stream_cloudiness = plotly.Stream(stream_id=token_2) stream_cloudiness.open() stream_rain = plotly.Stream(stream_id=token_3) stream_rain.open() streams = { 'temp': stream_temp, 'cloudiness': stream_cloudiness, 'rain': stream_rain, } return streams
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)