Пример #1
0
def generateAppPermissionsRequestedFrequencyHistogram(username, apiKey):
    permCountDict = extractAppPermData()
    permCount = []
    permCountFreq = []
    for permissionCount, permissionCountFreq in permCountDict.iteritems():
        permCount.append(permissionCount)
        permCountFreq.append(permissionCountFreq)

    tls.set_credentials_file(username, apiKey)
    trace = Bar(x=permCount,
                y=permCountFreq,
                name='App frequency',
                marker=Marker(color='rgb(55, 83, 109)'))
    data = Data([trace])
    layout = Layout(title='App Frequency vs Number of Permissions requested',
                    xaxis=XAxis(title='Number of Permissions requested',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    yaxis=YAxis(title='App frequency',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    legend=Legend(x=0,
                                  y=1.0,
                                  bgcolor='rgba(255, 255, 255, 0)',
                                  bordercolor='rgba(255, 255, 255, 0)'),
                    barmode='group',
                    bargap=0.15,
                    bargroupgap=0.1)
    fig = Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='app-perm')
    logging.debug('Check out the URL: ' + plot_url + ' for your plot')
Пример #2
0
    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()
Пример #3
0
def generatePlotSilhouette(username, apiKey, clusterCountList,
                           silhouetteAvgList, postfix):
    tls.set_credentials_file(username, apiKey)
    trace = Bar(x=clusterCountList,
                y=silhouetteAvgList,
                name='Silhouette Average Score',
                marker=Marker(color='rgb(0, 255, 0)'))
    data = Data([trace])
    layout = Layout(title='Number of Clusters vs Silhouette Average Score',
                    xaxis=XAxis(title='Number of Clusters',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    yaxis=YAxis(title='Silhouette Average Score',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    legend=Legend(x=0,
                                  y=1.0,
                                  bgcolor='rgba(255, 255, 255, 0)',
                                  bordercolor='rgba(255, 255, 255, 0)'),
                    barmode='group',
                    bargap=0.15,
                    bargroupgap=0.1)
    fig = Figure(data=data, layout=layout)
    name = 'silhouette-average-score'
    if postfix != None:
        name += postfix
    plot_url = py.plot(fig, filename=name)
    logging.debug('Check out the URL: ' + plot_url + ' for your plot')
Пример #4
0
def scatterplot_1d(data, mask):
    tls.set_credentials_file(username=PLOTLY_USER, api_key=PLOTLY_AUTH)

    traces = []
    #names = ['Vegetables', 'Fruits', 'Nuts, Seeds, and Legumes', 'Dairy', 'White Meat', 'Red Meat']
    #names = ['Plant', 'Animal']
    names = ['Low', 'Medium', 'High']

    for n in range(max(mask) + 1):
        x = data[mask == n, 0]
        y = np.full((1, len(x)), n).flatten()
        trace = Scatter(x=x,
                        y=y,
                        mode='markers',
                        name=names[n],
                        marker=Marker(size=12,
                                      line=Line(
                                          color='rgba(217, 217, 217, 0.14)',
                                          width=0.5),
                                      opacity=0.5))
        traces.append(trace)

    MyLayout = Layout(xaxis=layout.XAxis(showline=False),
                      yaxis=layout.YAxis(showline=False))
    return Figure(data=traces, layout=MyLayout)
Пример #5
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()
Пример #6
0
def account():
    ''' If the user does not have a plotly credential file, this function creates one for them. Uses plotly syntax.'''
    user = input("What is your username:  "******"Please enter the API key for your account:  ")
    tools.set_credentials_file(username=user, api_key=API)
    print("Congrats. Your credentials file has been set.")
    mainprogram()
Пример #7
0
def init(username=None, api_key=None, notebook_mode=False):
    """Establishes connection to plot.ly with the correct credentials.

    Args:
        username: Defaults to None
        api_key: Defaults to None
        notebook_mode (bool): Defaults to False

    Raises:
        RuntimeError: If no credential is provided, either as arguments
            or as a viz.conf config file in the working directory.
    """
    if username is None or api_key is None:
        if os.path.exists('vizz.conf'):
            print 'yay!'
        else:
            raise RuntimeError('')
    elif username is not None and api_key is not None:
        set_credentials_file(username=username, api_key=api_key)

    if notebook_mode:
        init_notebook_mode(connected=True)

    global layout
    layout = layout_def
Пример #8
0
def draw_hermite(n, a, b, nodes, *args):
    func_values = [values(func, n, a, b) for func in args]

    xvalues = values(lambda x: x, n, a, b)

    traceHermite = go.Scatter(
        x=xvalues,
        y=func_values[1],
        mode='markers',
        name='Hermite'
    )
    traceFunc = go.Scatter(
            x=xvalues,
            y=func_values[0],
            mode='markers',
            name='Original function'
        )
    xi, yi = zip(*nodes)
    traceCoordinates = go.Scatter(
        x=xi,
        y=yi,
        mode='markers',
        name='Nodes',
        marker=dict(
            size=15,
            color='rgba(0,0,0, 1)'
        )
    )

    data = [traceHermite, traceFunc, traceCoordinates]

    tls.set_credentials_file(username='******', api_key='e78ht2ggmf')
    py.plot(data, filename='plot' + str(len(nodes)))
Пример #9
0
 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")
Пример #10
0
def draw_func(n, a, b, plotly=False, sepplots=False, coordinates=None, *args):
    func_values = [values(func, n, a, b) for func in args]

    xvalues = values(lambda x: x, n, a, b)

    plt.figure(1)
    i = 211
    j = 0
    for vals in func_values:
        if sepplots:
            plt.subplot(i)
            i += 1
        plt.plot(xvalues, vals, plot_types[j], linewidth=2.0)
        j += 1

    plt.show()

    if not plotly:
        return

    traceNewton = go.Scatter(
        x=xvalues,
        y=func_values[0],
        mode='markers',
        name='Newton'
    )
    traceLagrange = go.Scatter(
        x=xvalues,
        y=func_values[1],
        mode='markers',
        name='Lagrange'
    )
    xi, yi = zip(*coordinates)
    traceCoordinates = go.Scatter(
        x=xi,
        y=yi,
        mode='markers',
        name='Nodes',
        marker=dict(
            size=15,
            color='rgba(0,0,0, 1)'
        )
    )
    if len(args) > 2:
        traceFunc = go.Scatter(
            x=xvalues,
            y=func_values[2],
            mode='markers',
            name='Original function'
        )
    if len(args) > 2:
        data = [traceNewton, traceLagrange, traceFunc, traceCoordinates]
    else:
        data = [traceNewton, traceLagrange, traceCoordinates]

    tls.set_credentials_file(username='******', api_key='e78ht2ggmf')
    py.plot(data, filename='plot' + str(n))
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)
Пример #12
0
def to_plotly():
    import plotly.plotly as py
    py.sign_in('nehasprasad', 'aqesi8eh7r')
    import plotly.tools as tls
    tls.set_credentials_file(username='******', api_key='aqesi8eh7r')
    from plotly.graph_objs import *

    temperatures, humidities, timezone, from_date_str, to_date_str = get_records(
    )

    # Create new record tables so that datetimes are adjusted back to the user browser's time zone.
    time_series_adjusted_tempreratures = []
    time_series_adjusted_humidities = []
    time_series_temprerature_values = []
    time_series_humidity_values = []

    for record in temperatures:
        local_timedate = arrow.get(record[0], "YYYY-MM-DD HH:mm").to(timezone)
        time_series_adjusted_tempreratures.append(
            local_timedate.format('YYYY-MM-DD HH:mm'))
        time_series_temprerature_values.append(round(record[2], 2))

    for record in humidities:
        local_timedate = arrow.get(record[0], "YYYY-MM-DD HH:mm").to(timezone)
        time_series_adjusted_humidities.append(
            local_timedate.format(
                'YYYY-MM-DD HH:mm'))  #Best to pass datetime in text
        #so that Plotly respects it
        time_series_humidity_values.append(round(record[2], 2))

    temp = Scatter(x=time_series_adjusted_tempreratures,
                   y=time_series_temprerature_values,
                   name='Temperature')
    hum = Scatter(x=time_series_adjusted_humidities,
                  y=time_series_humidity_values,
                  name='Humidity',
                  yaxis='y2')

    data = Data([temp, hum])

    layout = Layout(title="Temperature and Humidity in Clayton's Apartment",
                    xaxis=XAxis(type='date', autorange=True),
                    yaxis=YAxis(title='Fahrenheit',
                                type='linear',
                                autorange=True),
                    yaxis2=YAxis(title='Percent',
                                 type='linear',
                                 autorange=True,
                                 overlaying='y',
                                 side='right'))
    fig = Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='lab_temp_hum')

    return plot_url
Пример #13
0
def main():
    tools.set_credentials_file(username='******',
                               api_key='eWEiOWPqQYFUrS0xiNmo')
    date = datetime.datetime.now()
    dates_timestamps, dates_list = get_timestamp_tuple(date)
    all_posts_counts = []
    for timestamp in dates_timestamps:
        posts_data = get_posts(timestamp)
        current_count = posts_data['response']['total_count']
        all_posts_counts.append(current_count)
    create_graph(all_posts_counts, dates_list)
Пример #14
0
def run(log_file_s=basestring,
        auto_open=None,
        plotly_login=None,
        api_key=None):
    if not tls.get_credentials_file():
        print 'Please set your plotly login and api_key or give as additional arguments'
    if plotly_login and api_key:
        tls.set_credentials_file(plotly_login, api_key)
        logger.info('\nCredentials file is updated')
    draw_graph(log_file_s, auto_open=auto_open)
    logger.info('\nGraphs was drawn successfully\n')
Пример #15
0
def enable_plotly_in_cell():
    import IPython
    from plotly.offline import init_notebook_mode
    from plotly import tools
    #Descomentar esta linea en colab
    display(
        IPython.core.display.HTML(
            '''<script src="/static/components/requirejs/require.js"></script>'''
        ))
    tools.set_credentials_file(username='******',
                               api_key='euOGc1f62ScWry0fPG8D')
    init_notebook_mode(connected=True)
Пример #16
0
def plotly_heatmap(mi):
	"""
	Given a list with the MI scores for all possible pairs of residues in the protein(s) sequence(s)
	creates a plotly heatmap.
	"""
	(username, api_key)= parse_config(config_file, "plotly")
	tls.set_credentials_file(username=username, api_key=api_key)
	data = [ go.Heatmap(
			z=mi,
			x=[i for i in range(len(mi))],
			y= [i for i in range(len(mi))]) ]
	plot_url = py.plot(data, filename = 'mi_heatmap')
Пример #17
0
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
Пример #18
0
def setup():
    # Set plotly credentials
    pt.set_credentials_file(username='******', api_key=os.environ['API_KEY'])

    if os.path.isfile(csv_path):
        os.remove(csv_path)
    f = open(csv_path, 'a+')
    try:
        writer = csv.writer(f)
        writer.writerow(('Date', 'Stocks', 'Price($)'))
    finally:
        f.close()
Пример #19
0
def make_plot(logs, file_name):
    tls.set_credentials_file(username='******',
                                      api_key='wb1kstdv2f')
    x = [line['x'] for line in sorted(logs, key=lambda l: l['x'])]
    y = [line['y'] for line in sorted(logs, key=lambda l: l['x'])]
    trace = go.Scatter(
        x=x,
        y=y
    )
    data = [trace]

    plot_url = py.plot(data, filename=file_name, share='public')
    logger.info('Please visit this url: %s', plot_url)
Пример #20
0
 def __init__(self, testData=None, predictions=None, userData=None, allBusinessModels=None):
     tls.set_credentials_file(username='******', api_key='pic17ydt8e')
     self.allBusinessModels = allBusinessModels
     self.testData = testData
     self.predictions = predictions
     self.user = userData
     self._businessLatList = []
     self._businessLonList = []
     self._businessRatingList = []
     self._businessTextList = []
     self._predictionRatingList = []
     self._predictionLonList = []
     self._predictionLatList = []
     self._predictionTextList = []
Пример #21
0
def generatePermissionsRequestedByAppFrequencyHistogram(username, apiKey):
    dbHandle = databaseHandler.dbConnectionCheck()  #DB Open

    #	 crawlUrl(dbHandle, "https://raw.githubusercontent.com/android/platform_frameworks_base/master/core/res/AndroidManifest.xml")
    #	 sys.exit(1)

    cursor = dbHandle.cursor()
    sqlStatement = "SELECT * FROM `perm_app_count_view` LIMIT 25;"
    try:
        cursor.execute(sqlStatement)
        if cursor.rowcount > 0:
            queryOutput = cursor.fetchall()
            appCount = []
            permName = []
            for row in queryOutput:
                appCount.append(row[0])
                permName.append(row[1])
    except:
        logging.debug('Unexpected error:' + sys.exc_info()[0])
        raise

    dbHandle.close()  #DB Close

    tls.set_credentials_file(username, apiKey)
    tracePerm = Bar(x=permName,
                    y=appCount,
                    name='App frequency count',
                    marker=Marker(color='rgb(55, 83, 100)'))
    data = Data([tracePerm])
    layout = Layout(title='Permission vs App frequency count',
                    xaxis=XAxis(title='Permission',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    yaxis=YAxis(title='App frequency',
                                titlefont=Font(size=16,
                                               color='rgb(107, 107, 107)'),
                                tickfont=Font(size=14,
                                              color='rgb(107, 107, 107)')),
                    legend=Legend(x=0,
                                  y=1.0,
                                  bgcolor='rgba(255, 255, 255, 0)',
                                  bordercolor='rgba(255, 255, 255, 0)'),
                    barmode='group',
                    bargap=0.15,
                    bargroupgap=0.1)
    fig = Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='perm-app')
    logging.debug('Check out the URL: ' + plot_url + ' for your plot')
Пример #22
0
    def graph_parsed_data(self, username, api_key):

        """
         At this process the program will access the Plotly api and graph the features that/
        were given by the first parsing process. The attributes that it will take in will be Api Username,
        ApiPassword or api_key
        :param username: this accesses is the api Username that you initially added in the first process.
        :param api_key: this is the api key that you receive after registration.
        :return: Final graph
        """

        tls.set_credentials_file(username=username, api_key=api_key)
        data = [go.Scatter(x=self.df["jobs"], y=self.df["number of openings"])]  # assign x as the dataframe column 'x'
        final_graph = py.plot(data, filename="pandas/basic-bar")
        return final_graph
Пример #23
0
    def get_emp_graph(e_id):
        tls.set_credentials_file(username='******',
                                 api_key='OSTejAaNxLezI4RstNws')

        df = pd.DataFrame(
            list(
                AttendanceRecord.objects.filter(
                    emp_id=e_id, ).values().order_by('date')))

        df['in_time'] = df['in_time'].apply(
            lambda x: format(datetime.strptime(x, '%H:%M:%S'), '%H:%M:%S'))
        df['out_time'] = df['out_time'].apply(
            lambda x: format(datetime.strptime(x, '%H:%M:%S'), '%H:%M:%S'))

        df['date'] = df['date'].apply(
            lambda x: datetime.strptime(x, '%Y-%m-%d').date())
        df['miti'] = df['miti'].apply(
            lambda x: datetime.strptime(x, '%Y/%m/%d').date())

        print(df['in_time'])
        print(df['date'])

        trace1 = go.Scatter(
            x=df['date'],
            y=df['in_time'],
            name='In Time',
            mode='markers+lines',
            text=e_id,
            line=dict(color='#17BECF'),
        )

        trace2 = go.Scatter(
            x=df['date'],
            y=df['out_time'],
            name='Out Time',
            mode='markers+lines',
            text=e_id,
            line=dict(color='#7F7F7F'),
        )

        data = [trace1, trace2]
        layout = go.Layout(title="Time Analysis",
                           showlegend=True,
                           yaxis=dict(autorange=True))
        fig = go.Figure(data=data, layout=layout)
        div = plt.plot(fig, filename='d3', auto_open=False)
        print(div)
        return div
Пример #24
0
def plot(scatterlistx, scatterlisty, t0, t1, xtitle, ytitle):
    # Sign in to plotly
    pt.set_credentials_file(username='******', api_key='7iqvws7lp3')

    # For hypotheses line
    minxhypotheses = min(scatterlistx)
    maxxhypotheses = max(scatterlistx)
    xl = [minxhypotheses, maxxhypotheses]
    yl = [generatehypopoints(t0, t1, minxhypotheses), generatehypopoints(t0, t1, maxxhypotheses)]

    tracescatter = go.Scatter(
        x=scatterlistx,
        y=scatterlisty,
        mode='markers',
        name='scatter'
    )

    traceline = go.Scatter(
        x=xl,
        y=yl,
        mode='lines',
        name='gradientdescent'
    )

    data = [tracescatter, traceline]
    layout = go.Layout(
        title=xtitle + " vs " + ytitle,
        xaxis=dict(
            title=xtitle,
            titlefont=dict(
                family='Courier New, monospace',
                size=18,
                color='#7f7f7f'
            )
        ),
        yaxis=dict(
            title=ytitle,
            titlefont=dict(
                family='Courier New, monospace',
                size=18,
                color='#7f7f7f'
            )
        )
    )
    fig = go.Figure(data=data, layout=layout)

    url = py.plot(fig, filename=xtitle + ytitle)
    return url
Пример #25
0
def getPlotStation(pers, plotTitle, timezone):
    #	import plotly.plotly as py
    #   	from plotly.graph_objs import *
    #  	import plotly.tools as pyTools
    pyTools.set_credentials_file(username='******',
                                 api_key='jLRlCzSOlSOKuUtvknqD')

    time_series_adjusted = []
    time_series_values = []

    for record in pers:
        local_timedate = arrow.get(record[0], "YYYY-MM-DD HH:mm").to(timezone)
        time_series_adjusted.append(local_timedate.format('YYYY-MM-DD HH:mm'))
        time_series_values.append(round(record[2], 2))

    per = Scatter(x=time_series_adjusted, y=time_series_values, name=plotTitle)

    data = Data([per])  # change from Data([temp, hum]) --> Data([temp])

    layout = Layout(
        title=plotTitle,
        xaxis=XAxis(type='date', autorange=True),
        yaxis=YAxis(title='Number of People', type='linear', autorange=True),
    )
    fig = Figure(data=data, layout=layout)

    with Switch(plotTitle) as case:
        if case("Persian Station"):
            plot_url = py.plot(fig, filename='persian_station_C4C')
            print "Ploting Persian"
        if case("Asian Station"):
            plot_url = py.plot(fig, filename='asian_station_C4C')
            print "Ploting Asia"
        if case("Italian Station"):
            plot_url = py.plot(fig, filename='italian_station_C4C')
            print "Ploting Italian"
        if case("American Station"):
            plot_url = py.plot(fig, filename='american_station_C4C')
            print "Ploting American"
        if case("Latin Station"):
            plot_url = py.plot(fig, filename='latin_staion_C4C')
            print "Ploting Latin"

    print "Finishing ", plotTitle

    return [plot_url, per]
Пример #26
0
    def graphing_salary(self, username, api_key):
        '''

        :param username: str. This is the Plotly api username that you gave beforehand
        :param api_key: str. Plotly api_key
        :return: graphical output of the job selected.
        '''

        # authorizing the user Plotly credentials
        tls.set_credentials_file(username=username, api_key=api_key)

        # creating a Plotly scatter object
        data = [
            go.Scatter(x=self.df5['Quantity'], y=self.df5['Salary from jobs'])
        ]
        final_graph = py.plot(data, filename='pandas/basic-bar')
        return final_graph
Пример #27
0
def tsne_plotly(data, cat, labels, source, username, api_key, seed=0,
                max_points_per_category=250, max_label_length=64):
    print("Plotting data...")
    set_credentials_file(username=username, api_key=api_key)
    model = TSNE(n_components=3, random_state=seed, verbose=1)
    reduced = model.fit_transform(data)

    # subsample points before tsne / plotting
    if False:
        new_data = []
        new_cats = []
        for n in np.unique(cat):
            idx = np.where(cat == n)[0]
            idx = idx[:max_points_per_category]
            new_data.append(data[idx])
            new_cats.append(np.reshape(cat[idx], [cat[idx].size, 1]))
        data = np.vstack(new_data)
        cat = np.vstack(new_cats)
        cat = np.reshape(cat, (cat.size,))
    labels = np.asarray([lbl[:max_label_length] for lbl in labels])
    plot_params = [
        [reduced, source, labels[cat], 'topics-scatter.html'],
        [reduced, labels[cat], source, 'source-scatter.html']]

    # general figure layouts these are default values
    layout = go.Layout(
        margin=dict(
            l=0,
            r=0,
            b=0,
            t=0
        )
    )

    # generating figures
    figures = []
    for data, hover_text, cats, fname in plot_params:
        fig = gen_plotly_specs(datas=data, hover_text=hover_text, cat=cats)

        plotly.offline.plot({
            "data": fig,
            "layout": layout
        }, filename=fname)

        figures.append([fig, fname])
Пример #28
0
    def graph_parsed_data(self, username, api_key):
        '''
         At this process the program will access the Plotly api and graph the features that/
        were given by the first parsing process. The attributes that it will take in will be Api Username,
        ApiPassword or api_key
        :param username: this accesses is the api Username that you initially added in the first process.
        :param api_key: this is the api key that you receive after registration.
        :return: Final graph
        '''

        tls.set_credentials_file(username=username, api_key=api_key)
        data = [
            go.Scatter(
                x=self.df['jobs'],  # assign x as the dataframe column 'x'
                y=self.df['number of openings'])
        ]
        final_graph = py.plot(data, filename='pandas/basic-bar')
        return final_graph
Пример #29
0
 def __init__(self,
              testData=None,
              predictions=None,
              userData=None,
              allBusinessModels=None):
     tls.set_credentials_file(username='******', api_key='pic17ydt8e')
     self.allBusinessModels = allBusinessModels
     self.testData = testData
     self.predictions = predictions
     self.user = userData
     self._businessLatList = []
     self._businessLonList = []
     self._businessRatingList = []
     self._businessTextList = []
     self._predictionRatingList = []
     self._predictionLonList = []
     self._predictionLatList = []
     self._predictionTextList = []
Пример #30
0
def choropl_viols(values, fips, leg='Violations by County'):
    """
    Inputs: values: list of values to be mapped
            fips:list of fips codes for each county mapped
            leg: Title to be used in legend
    """
    endpts = list(np.mgrid[min(values):max(values):6j])

    colorscale = [
        'rgb(169,186,157)', 'rgb(208,240,192)', 'rgb(152,251,152)',
        'rgb(80,220,100)', 'rgb(0,168,107)', 'rgb(79,121,66)',
        'rgb(63,122,77)', 'rgb(46,139,87)', 'rgb(11,102,35)', 'rgb(0,78,56)'
    ]

    fig = ff.create_choropleth(
        fips=fips,
        values=values,
        scope=['North Carolina'],
        show_state_data=True,
        colorscale=colorscale,
        binning_endpoints=endpts,
        round_legend_values=True,
        plot_bgcolor='rgb(229,229,229)',
        paper_bgcolor='rgb(229,229,229)',
        legend_title=leg,  #legend_title='Violations by County',
        county_outline={
            'color': 'rgb(255,255,255)',
            'width': 0.5
        },
        #exponent_format=True,
    )
    fig['layout']['legend'].update({'x': 0})
    fig['layout']['annotations'][0].update({'x': -0.12, 'xanchor': 'left'})

    ptools.set_credentials_file(api_key=secrets2.AppKey['Plotly'],
                                username=secrets2.uzer_name['Plotly'])

    name3 = (leg.split(' ')[-1]) + 'LnkDNtstFri10am'

    py.plot(fig, filename=name3, auto_open=True)
    pio.write_image(fig, name3 + '.png')

    return
Пример #31
0
 def __init__(self,choose_stream_id, filename, title):
     self.filename = filename
     self.title = title
     self.dataX = 0.0
     self.dataY = 0.0
     
     py.sign_in('tachagon', 'e3xdl3rnqe')
     stream_ids=["5oedue6mq7", "thg9gb1wwd", "p8x1frf0qx"]
     tls.set_credentials_file(stream_ids)
     
     # Get stream id from stream id list
     stream_id = stream_ids[choose_stream_id]
     # 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',
         stream=stream       # embed stream id, 1 per trace
     )
     
     data = Data([trace1])
     
     # Add title to layout object
     layout = Layout(title=self.title)
     
     # 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=self.filename)
     
     # (@)   Make instance of the Stream link object,
     #       with same stream id as Stream id object
     self.s = py.Stream(stream_id)
     
     #(@) Open the stream
     self.s.open()
Пример #32
0
def to_plotly():
    #	import plotly.plotly as py
    #	from plotly.graph_objs import *
    # 	import plotly.tools as pyTools
    pyTools.set_credentials_file(username='******',
                                 api_key='jLRlCzSOlSOKuUtvknqD')

    Asian, American, Persian, Italian, Latin, timezone, from_date_str, to_date_str = get_records(
    )

    #################### Start Persian plot ##################
    print "About to start getting into the functions"
    [plot_url, per] = getPlotStation(Persian, "Persian Station", timezone)
    [plot_url2, asi] = getPlotStation(Asian, "Asian Station", timezone)
    [plot_url3, ita] = getPlotStation(Italian, "Italian Station", timezone)
    [plot_url4, usa] = getPlotStation(American, "American Station", timezone)
    [plot_url5, lat] = getPlotStation(Latin, "Latin Station", timezone)
    plot_all = getAllPlot(per, asi, ita, usa, lat)
    return plot_all
Пример #33
0
def getAllPlot(per, asi, ita, usa, lat):
    #	import plotly.plotly as py
    #        from plotly.graph_objs import *
    #        import plotly.tools as pyTools
    pyTools.set_credentials_file(username='******',
                                 api_key='jLRlCzSOlSOKuUtvknqD')

    data = Data([per, asi, ita, usa, lat])

    layout = Layout(
        title="Count of people for all stations",
        xaxis=XAxis(type='date', autorange=True),
        yaxis=YAxis(title='Number of People', type='linear', autorange=True),
    )

    fig = Figure(data=data, layout=layout)
    plot_all_url = py.plot(fig, filename='C4C_count')

    return plot_all_url
Пример #34
0
def make_plot():
    time, pm25, pm10 = get_data_from_db()
    plotly_username = conf["plotly"]["username"]
    plotly_key = conf["plotly"]["api_key"]
    plotly_filename = conf["plotly"]["filename"]
    plot_pm25 = go.Scatter(x=time, y=pm25, name="pm2.5")
    plot_pm10 = go.Scatter(x=time, y=pm10, name="pm10")
    set_credentials_file(username=plotly_username, api_key=plotly_key)
    out = plot(
        {
            "data": [plot_pm25, plot_pm10],
            "layout": layout
        },
        filename=plotly_filename,
        fileopt="overwrite",
        auto_open=False,
        sharing="public",
    )
    return out
Пример #35
0
def write(timestamp, temperatures):

    if invalidConfig:
        if plotly_debugEnabled:
            plotly_logger.debug('Invalid config, aborting write')
            return []

    debug_message = 'Writing to ' + plugin_name
    if not plotly_writeEnabled:
        debug_message += ' [SIMULATED]'
    plotly_logger.debug(debug_message)

    debug_text = '%s: ' % timestamp

    if plotly_writeEnabled:
        # Stream tokens from plotly
        tls.set_credentials_file(stream_ids=stream_ids_array)

    try:
        if plotly_writeEnabled:
            py.sign_in(plotly_username, plotly_api_key)

        for temperature in temperatures:
            debug_text += "%s (%s A" % (temperature.zone, temperature.actual)
            if temperature.target is not None:
                debug_text += ", %s T" % temperature.target
            debug_text += ') '

            if plotly_writeEnabled:
                if temperature.zone in zones:
                    stream_id = zones[temperature.zone]
                    s = py.Stream(stream_id)
                    s.open()
                    ts = timestamp.strftime('%Y-%m-%d %H:%M:%S')
                    s.write(dict(x=ts, y=temperature.actual))
                    s.close()
                else:
                    plotly_logger.debug(
                        "Zone %s does not have a stream id, ignoring")

    except Exception, e:
        plotly_logger.error("Plot.ly API error - aborting write\n%s", e)
Пример #36
0
def exercise09():
    '''
    Load historical Bitcoin prices that are in JSON format from https://api.coindesk.com/v1/bpi/historical/close.json using
    start date 9/1/2017 and end date 10/5/2018. Documentation on the API is here: https://www.coindesk.com/api/
    Note: You may need to use the requests library and header spoofing to grab the data and then giving it to a DataFrame 

    With the prices loaded into the DataFrame:

    - Drop the disclaimer column
    - Remove the bottom two rows
    - Plot a price timeseries and publish it to Plotly using the Plotly API and set the URL to the chart to the plotly_url variable.
    Publication to Plotly will occur programmtically via plotly API. You will need to import the library and create an API key from
    the plotly dashboard.
    - Print the head
    - Print the tail

    '''
    header = {
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
    }

    # ------ Place code below here \/ \/ \/ ------
    url = "https://api.coindesk.com/v1/bpi/historical/close.json?start=2017-09-01&end=2018-10-05"
    resp = requests.get(url=url, headers=header, verify=False)
    json = resp.json()['bpi']
    df = pd.Series(json)
    df_new = pd.DataFrame(df).reset_index()
    df_new.columns = ['Date', 'Value']

    data = [go.Scatter(x=df_new.Date, y=df_new['Value'])]
    tools.set_credentials_file(username=user_name, api_key=api_key)
    # py.iplot(data)
    plotly_url = py.plot(data, filename='basic-line', auto_open=True)
    print(plotly_url)
    df = df_new
    print(df.head())
    print(df.tail())

    # ------ Place code above here /\ /\ /\ ------
    return df, plotly_url
Пример #37
0
def write(timestamp, temperatures):

    if invalidConfig:
        if plotly_debugEnabled:
            plotly_logger.debug('Invalid config, aborting write')
            return []

    debug_message = 'Writing to ' + plugin_name
    if not plotly_writeEnabled:
        debug_message += ' [SIMULATED]'
    plotly_logger.debug(debug_message)

    debug_text = '%s: ' % timestamp

    if plotly_writeEnabled:
        # Stream tokens from plotly
        tls.set_credentials_file(stream_ids=stream_ids_array)

    try:
        if plotly_writeEnabled:
            py.sign_in(plotly_username, plotly_api_key)

        for temperature in temperatures:
            debug_text += "%s (%s A" % (temperature.zone, temperature.actual)
            if temperature.target is not None:
                debug_text += ", %s T" % temperature.target
            debug_text += ') '

            if plotly_writeEnabled:
                if temperature.zone in zones:
                    stream_id = zones[temperature.zone]
                    s = py.Stream(stream_id)
                    s.open()
                    ts = timestamp.strftime('%Y-%m-%d %H:%M:%S')
                    s.write(dict(x=ts, y=temperature.actual))
                    s.close()
                else:
                    plotly_logger.debug("Zone %s does not have a stream id, ignoring")

    except Exception, e:
        plotly_logger.error("Plot.ly API error - aborting write\n%s", e)
Пример #38
0
    def graphing_salary(self, username, api_key):
        '''

        :param username: str. This is the Plotly api username that you gave beforehand
        :param api_key: str. Plotly api_key
        :return: graphical output of the job selected.
        '''

        # authorizing the user Plotly credentials
        tls.set_credentials_file(username=username, api_key=api_key)

        # creating a Plotly scatter object
        data = [
            go.Scatter(
                x=self.df5['Quantity'],
                y=self.df5['Salary from jobs']

            )
        ]
        final_graph = py.plot(data, filename='pandas/basic-bar')
        return final_graph
Пример #39
0
def scatterplot_2d(data, labels):
    tls.set_credentials_file(username=PLOTLY_USER, api_key=PLOTLY_AUTH)

    traces = []
    names = list(set(labels))

    for name in names:
        x = data[labels == name, 0]
        y = data[labels == name, 1]
        trace = Scatter(x=x,
                        y=y,
                        mode='markers',
                        name=name,
                        marker=Marker(size=12,
                                      line=Line(
                                          color='rgba(217, 217, 217, 0.14)',
                                          width=0.5),
                                      opacity=0.5))
        traces.append(trace)

    MyLayout = Layout(xaxis=layout.XAxis(showline=False),
                      yaxis=layout.YAxis(showline=False))
    return Figure(data=traces, layout=MyLayout)
Пример #40
0
    def __init__(self, plotly_user, plotly_api_key, plotly_stream_tokens):
        self.plotly_user = plotly_user
        self.plotly_api_key = plotly_api_key

        # Colors will be mapped to streams in order
        self.colors = [
            'rgb(195,56,37)',  # Red   (high)
            'rgb(33,127,188)',  # Blue  (medium)
            'rgb(26,175,93)',  # Green (low)
            'rgb(143,63,176)',  # Purple
            'rgb(246,158,0))',  # Orange
            'rgb(43,61,81)',  # Navy Blue
            'rgb(214,84,0)'
        ]  # Pumpkin

        self.component_tag = 'component:'  # Component prefix (will be stripped on graph legend)
        self.state_tag = 'state:'  # State prefix (will be stripped on graph legend)
        self.priority_tag = 'priority:'  # State prefix (will be stripped on graph legend)

        # Prepare stream ids
        tls.set_credentials_file(username=self.plotly_user,
                                 api_key=self.plotly_api_key,
                                 stream_ids=plotly_stream_tokens)
        self.stream_tokens = tls.get_credentials_file()['stream_ids']
Пример #41
0
"""Plots a csv file indicating the activity and duration of the activity.
Will display bar graph on plotly."""

import csv
import numpy as np
import plotly.tools as tls
import plotly.plotly as py
from plotly.graph_objs import *
import convert

tls.set_credentials_file(username='******', api_key='....')

def data_entry():
	"""Return a plotly bar graph of the csv activities file."""

	x_axis = []
	y_axis = []

	# Read the csv file with the time values 
	with open('workfile.txt', 'r') as csvfile: 
		data_file = csv.reader(csvfile, delimiter='/')
		for row in data_file:
			x_axis.append(row[0])
			y_axis.append(convert.convert_tuple(row[1], 'hour'))

	# Create the Plotly Graph
	data = Data([
	    Bar(
	        x = x_axis,
	        y = y_axis
	    )
def plot_data(data_dict):
    '''
    Plots the data on the Plotly Framework.
    '''
    py.sign_in(plotly_username, plotly_api_key)
    tls.set_credentials_file(username=plotly_username,
                                 api_key=plotly_api_key)
    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, data_dict["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=[data_dict["width"], 0],
                    autorange=False,
                    autotick=False,
                    dtick=15,
                    tickangle=-45,
                    title="Y co-ordinate"
                    )
                )
    mac_history_data = data_dict['data']
    processed_data = []
    for mac, p_data in mac_history_data.items():
        if len(p_data):
            p_data = sorted(p_data, key=lambda x:x[0])
            color = color_generator()
            plot_data = Scatter(
                x=[x[1] for x in p_data],
                y=[y[2] for y in p_data],
                mode='lines + text',
                text=list(range(1, len(p_data) + 1)),
                name=mac,
                marker=Marker(color=color),
                opacity="0.6",
                legendgroup = mac,
            )
            processed_data.append(plot_data)
            
            startData = Scatter(
            x=[p_data[0][1]],
            y=[p_data[0][2]],
            mode='markers',
            marker=Marker(color=color, size="10", symbol = "triangle-left"),
            showlegend=False,
            text=["Start point " + mac],
            legendgroup=mac,
            )
            processed_data.append(startData)
            
            endData = Scatter(
            x=[p_data[-1][1]],
            y=[p_data[-1][2]],
            mode='markers',
            marker=Marker(color=color, size="10"),
            showlegend=False,
            text=["End point " + mac],
            legendgroup=mac,
            )
            processed_data.append(endData)
    data = Data(processed_data)
    fig = Figure(data=data, layout=layout)
    py.plot(fig, filename='Sample Code For History Of Clients ')
Пример #43
0
    def accept(self):

        # In future we might be able to use more fine-grained exceptions
        # https://github.com/plotly/plotly.py/issues/524

        self.set_status('Signing in and plotting...', color='blue')

        auth = {}

        if self.ui.radio_account_glue.isChecked():
            auth['username'] = '******'
            auth['api_key'] = 't24aweai14'
        elif self.ui.radio_account_config.isChecked():
            auth['username'] = ''
            auth['api_key'] = ''
        else:
            if self.username == "":
                self.set_status("Username not set", color='red')
                return
            elif self.api_key == "":
                self.set_status("API key not set", color='red')
                return
            else:
                auth['username'] = self.username
                auth['api_key'] = self.api_key

        from plotly import plotly
        from plotly.exceptions import PlotlyError
        from plotly.tools import set_credentials_file

        # Signing in - at the moment this will not check the credentials so we
        # can't catch any issues until later, but I've opened an issue for this:
        # https://github.com/plotly/plotly.py/issues/525
        plotly.sign_in(auth['username'], auth['api_key'])

        if self.ui.radio_sharing_public.isChecked():
            self.plotly_kwargs['sharing'] = 'public'
        elif self.ui.radio_sharing_secret.isChecked():
            self.plotly_kwargs['sharing'] = 'secret'
        else:
            self.plotly_kwargs['sharing'] = 'private'

        # We need to fix URLs, so we can't let plotly open it yet
        # https://github.com/plotly/plotly.py/issues/526
        self.plotly_kwargs['auto_open'] = False

        # Get title and legend preferences from the window
        self.plotly_args[0]['layout']['showlegend'] = self.legend
        self.plotly_args[0]['layout']['title'] = self.title

        try:
            plotly_url = plotly.plot(*self.plotly_args, **self.plotly_kwargs)
        except PlotlyError as exc:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            if "the supplied API key doesn't match our records" in exc.args[0]:
                username = auth['username'] or plotly.get_credentials()['username']
                self.set_status("Authentication with username {0} failed".format(username), color='red')
            elif "filled its quota of private files" in exc.args[0]:
                self.set_status("Maximum number of private plots reached", color='red')
            else:
                self.set_status("An unexpected error occurred", color='red')
            return
        except:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            self.set_status("An unexpected error occurred", color='red')
            return

        self.set_status('Exporting succeeded', color='blue')

        if self.save_settings and self.ui.radio_account_manual.isChecked():
            try:
                set_credentials_file(**auth)
            except Exception:
                print("Plotly exception:")
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
                self.set_status('Exporting succeeded (but saving login failed)', color='blue')

        # We need to fix URL
        # https://github.com/plotly/plotly.py/issues/526
        if self.plotly_kwargs['sharing'] == 'secret':
            pos = plotly_url.find('?share_key')
            if pos >= 0:
                if plotly_url[pos - 1] != '/':
                    plotly_url = plotly_url.replace('?share_key', '/?share_key')

        print("Plotly URL: {0}".format(plotly_url))

        webbrowser.open_new_tab(plotly_url)

        super(QtPlotlyExporter, self).accept()
Пример #44
0
__author__ = 'Lothilius'

from Helpdesk import Helpdesk
from SFDC import SFDC
import pandas as pd
import datetime
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
import re

tls.set_credentials_file(username='******', api_key='')
pd.set_option('display.width', 160)

def convert_time(unicode_series):
    """Given value for date time
        Convert it to a regular datetime string"""
    # for each in unicode_series:
    if len(unicode_series) == 10:
        pass
    elif len(unicode_series) == 13:
        unicode_series = unicode_series[:10]
    try:
        date_time_value = datetime.datetime.fromtimestamp(int(unicode_series)).strftime('%Y-%m-%d')
        if int(date_time_value[:4]) > 2009:
            return date_time_value
        else:
            return unicode_series
    except:
        return unicode_series
#initialize the Twilio API
client = TwilioRestClient(account = 'ACdcfe2835ebc3cc5a64b326abe1d5f4d0', 
	token = '0dfd8f8b7d00c2f282156422e7a625fd')

#initialize inputs from RPi and circuit board
GPIO.setmode(GPIO.BCM)
GPIO.setup(04, GPIO.IN)

#initialize credentials for Plotly API
py.sign_in('atomicwest', 'e8q2zycckg')

#embed streaming plot
#tls.embed('streaming-demos','6')

tls.set_credentials_file(username='******', api_key='e8q2zycckg')
tls.set_credentials_file(stream_ids=["gc1co66vqa", "dddgcrbmrk", "l0arxz77g6",
	 "uigxym0iqj", "1337subfep"])

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

print stream_ids

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

#make instance of stream id object
stream = Stream(
	token = stream_id,
	maxpoints = 50
)
Пример #46
0
from plotly import plotly, tools
import key
import plotly.plotly as py
from plotly.graph_objs import *
import stdtable

tools.set_credentials_file(username=key.username, api_key=key.apikey)

def tutorial():

    trace0 = Scatter(
        x=[1, 2, 3, 3],
        y=[10, 15, 13, 17],
        mode="markers"
    )
    trace1 = Scatter(
        x=[1, 2, 3, 4],
        y=[16, 5, 11, 9],
        mode="markers"
    )
    data = Data([trace0, trace1])

    layout = Layout(
        xaxis = dict(title=""),
        yaxis = dict(title="")
    )
    fig = Figure(data=data, layout=layout)

    py.plot(fig, filename=chartname)

def interval_by_hour(timeslice_dict, chartname="interval_by_hour.html"):
#config
Config = ConfigParser.ConfigParser()
Config.read("config.ini")
Username = Config.get('Plotly', 'Username')
APIkey = Config.get('Plotly', 'APIkey')

# Sign in
py.sign_in(Username, APIkey)

stream_ids_array = []
for name, value in Config.items('Rooms'):
    stream_ids_array.append(value)

# Stream tokens from plotly
tls.set_credentials_file(stream_ids=stream_ids_array)
stream_ids = tls.get_credentials_file()['stream_ids']

# Set your login details in the 2 fields below
USERNAME = Config.get('Evohome', 'Username')
PASSWORD = Config.get('Evohome', 'Password')

try:
    client = EvohomeClient(USERNAME, PASSWORD)
except ValueError:
    try:
        client = EvohomeClient(USERNAME, PASSWORD)
    except ValueError:
        print "Error when connecting to internet, please try again"

# We make a plot for every room
Пример #48
0
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls

tls.set_credentials_file(username='******', api_key='k0aql2lhru')


class Chart(object):
	"""A class that makes charts."""
	def __init__(self, name, chart_type, data):
		self.name = name
		self.type = chart_type
		self.data = data
	
	def plot(self):
		print 'Plotting chart...'
		trace1 = go.Scatter(
			x=self.data[0],
			y=self.data[3],
			mode='markers'
		)

		trace2 = go.Scatter(
			x=self.data[0],
			y=self.data[1],
			mode='markers'
		)
		data = [trace1, trace2]
		if self.name == '':
			self.name = 'default_plot'
		plot_url = py.plot(data, filename=self.name)
Пример #49
0
def plotData(data_dict):
    '''
    Plots the data on the Plotly Framework.
    '''
    pData = data_dict['data']
    pData = sorted(pData, key=lambda x:x[0])
    
    processed_data = Scatter(
        x=[x[1] for x in pData],
        y=[y[2] for y in pData],
        mode='lines + text',
        text=list(range(1, len(pData) + 1)),
        name=mac,
        marker=Marker(color="red"),
        opacity="0.5",
        legendgroup = mac,
    )
    
    startAndEndData = Scatter(
        x=[pData[0][1], pData[-1][1]],
        y=[pData[0][2], pData[-1][2]],
        mode='markers',
        marker=Marker(color="red", size="6"),
        showlegend=False,
        name = mac,
        text=["Start point", "End point"],
        legendgroup = mac,
    )

    py.sign_in(plotly_username, plotly_api_key)
    tls.set_credentials_file(username=plotly_username,
                                 api_key=plotly_api_key)
    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, data_dict["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=[data_dict["width"], 0],
                    autorange=False,
                    autotick=False,
                    dtick=15,
                    tickangle=-45,
                    title="Y co-ordinate"
                    )
                )
    data = Data([processed_data,startAndEndData])
    fig = Figure(data=data, layout=layout)
    py.plot(fig, filename='Sample Code For History Of Clients ')
Пример #50
0
#Count number of ALL tweets per day
i = 0
temp = date[0]
for i in range(len(date)):
    if temp == date[i]:
        count = count + 1
        i = i + 1
    else:
        x.append(temp)
        yx.append(count)
        temp = date[i]
        count = 1

tls.set_credentials_file(stream_ids=[
        "r510f777cl"
    ])

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(
Пример #51
0
     start = c * interval + 1
 
 conn = HTTPPasswordMgrWithDefaultRealm()
 conn.add_password(None, URL, username, password)
 handler = HTTPBasicAuthHandler(conn)
 opener = build_opener(handler)
 opener.addheaders = [('Accept', 'application/' + response_format)]
 install_opener(opener)
 page = urlopen(URL).read()
 page = page.decode('utf-8')
 data_dict = get_useful_data_from_json(page)
 mainDict["data"].extend(data_dict["data"])
 if totalpages is None:
     totalpages = data_dict.get("totalPages")
     py.sign_in(plotly_username, plotly_api_key)
     tls.set_credentials_file(username=plotly_username,
                                  api_key=plotly_api_key)
     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,
Пример #52
0
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.graph_objs import *
import numpy as np
import plotly.tools as tls
tls.set_credentials_file(username='******', api_key='mxg1wama31')

a = np.load('results/r_50nr_0ns_0lambda_100.npy')

data = [go.Surface(z=a)]

layout = go.Layout(
    title='Shape from Shading',
    autosize=False,
    width=500,
    height=500,
    scene=Scene(
        xaxis=dict(
            autorange=False,
            range=[0, 50]  # set axis range
        ),
        yaxis=dict(
            autorange=False,
            range=[0, 50]
        ),
        zaxis=dict(
            autorange=False,
            range=[0,50]
        )
    ),
    margin=dict(
Пример #53
0
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import pprint

username = '******'
api_key  = '799l3tg6mq'
tls.set_credentials_file(username=username, api_key=api_key)

MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

# Returns a boolean denoting whether the given year is a leap year or not
def isLeapYear(year):
	return year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0)

# Converts a slash-delimited date into a float
def dateScore(date):
	if date.find('/') == -1:
		"Incorrect date format."
		exit(1)

	month, day, year = map(float, date.split('/'))
	monthBuffer = sum(MONTH_LENGTHS[x] for x in xrange(0, int(month) - 1))
	monthBuffer += 1 if isLeapYear(year) and month == 2 else 0
	return year + (monthBuffer + day) / 365.0

# Creates a graph to visualize the given celebrity's film scores
def createGraph(data):
	traces = []
	releaseDates = []
	rtScores     = []
Пример #54
0
AAAA.01.01     001 
"""
import os
import pymodis
import subprocess 
from osgeo import gdal
import datetime
import csv
import numpy as np

import plotly.tools as tls
import plotly.plotly as py
from plotly.graph_objs import *

#####plotly credential################
tls.set_credentials_file(username="******",api_key="ct5xumzsfx")
stream_token_series='ciwtg2uycs'
stream_token_anomaly='y5r7tudz8g'
######################################
########plotly setting################
trace_series = Scatter(x=[],y=[],stream=Stream(token=stream_token_series),yaxis='y',name='NDVI series')
trace_anomaly = Scatter(x=[],y=[],stream=Stream(token=stream_token_anomaly),yaxis='y2',name='NDVI anomaly index')
layout = Layout(title='NDVI MODIS Streaming data for Olea auropea in Umbria region (Italy)',
	yaxis=YAxis(title='NDVI index'),
	yaxis2=YAxis(title='Anomaly',side='right',overlaying="y"
	)
)

fig = Figure(data=[trace_series,trace_anomaly], layout=layout)
print py.plot(fig, filename='NDVI MODIS Streaming data for Olea auropea')
########settings######################
Пример #55
0
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 *
 
import numpy as np  # (*) numpy for math functions and arrays
import pandas as pd
import matplotlib.pyplot as plt
import datetime 
import time 
import sys

tls.set_credentials_file(username="******", api_key="x4kt8y1smu")



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

stream_id1 = stream_ids[0]
stream_id2 = stream_ids[1]
stream_id3 = stream_ids[2]

stream_id4 = stream_ids[3]
stream_id5 = stream_ids[4]
stream_id6 = stream_ids[5]

stream_id7 = stream_ids[6]
stream_id8 = stream_ids[7]
#packages to import
import numpy as np
import scipy.io as sio
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
from frequencyFunction_specific import FrequencySpecific
from category import category
from PositionFunction_General import Position_general
tls.set_credentials_file(username='******', api_key='9xknhmjhas')


def CategoryTrainingFigure_Funnel(fileDirectory, filename, session):
    #Use when debugging or manually editing
    #filename      = ('20160630_1430-MR1040_block6')
    #fileDirectory = '/Users/courtney/GoogleDrive/Riesenhuber/05_2015_scripts/Vibrotactile/01_CategoryTraining/data/1040/'
    #session       = '2'

    #load matfile
    data = sio.loadmat(fileDirectory + filename, struct_as_record=True)

    #pull relevant data from structures
    reactionTime = data['trialOutput']['RT']
    sResp = data['trialOutput']['sResp']
    correctResponse = data['trialOutput']['correctResponse']
    accuracy = data['trialOutput']['accuracy']
    level = data['trialOutput']['level']
    stimuli = data['trialOutput']['stimuli']
    nTrials = data['exptdesign']['numTrialsPerSession'][0, 0][0]
    nBlocks = data['exptdesign']['numSessions'][0, 0][0]
    subjectName = data['exptdesign']['subName'][0, 0][0]
# This class creates the graphs
# We used Flask to display the graph in HTML


import dataAnalysis
import plotly.plotly as py
from plotly.graph_objs import *
import plotly.tools as tls
import numpy as np
from flask import Flask, render_template, request
from aParser import aParser
from send_email import email
import Dictionary
import random
from numpy import integer
tls.set_credentials_file(username = '******', api_key = 'jqwnqq7qkh')
app = Flask(__name__, static_url_path="/static")


x = aParser()
tempString = '56070b7de9a2530d0016bda3'
x.setChild(tempString)
x.getBalance()
x.addBalanceToChildAcc(3000)
for i in Dictionary.BestBuy_Array:
    x.spending(i.name, i.price, int (random.random() * 15))
for i in Dictionary.AmericanEagle_Array:
    x.spending(i.name, i.price, int (random.random() * 15))
for y in Dictionary.WholeFoods_Array:
    for i in Dictionary.WholeFoods_Array:
        x.spending(i.name, i.price, int (random.random() * 15))