Example #1
0
    def plot_results(self):
        """
        Plot historical ranking
        """
        #plots = []
        import plotly.plotly as py
        import plotly.graph_objs as go
        plots_py = []
        player_names = self.get_player_names_sorted()
        for name in player_names:
            player_evolution = self.get_player_evolution(name)
            indexes    = [int(i) for i in player_evolution]
            indexes_py = [str(self.all_daily_results[d].get_date()) for d in player_evolution.keys()]
            indexes.sort()
            indexes_py.sort()
            y_axis_data = [player_evolution[str(i)] for i in indexes]
            #plots.extend(plt.plot(indexes, y_axis_data, Color.get_color(), label=name))
            plots_py.append(go.Scatter(x=indexes_py, y=y_axis_data, mode='lines+markers', name=name))

            layout = go.Layout(
                title='Basket USA Fantasy historic',
                xaxis=dict(title='',
                           titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')
                           ),
                yaxis=dict(title='Pts',
                           titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')
                           )
            )

        fig = go.Figure(data=plots_py, layout=layout)
        py.plot(fig, filename='busa')
def plotlyUpload(table, columns, title, ylabel, limits, file_name, 
                 use_columns=columns, online=False):
    con = sqlite3.connect(
    "C:\ProgramData\ForSens\Projekte\StuttgarterBruecke\Data\Data.db3")
    
    df = pd.read_sql("SELECT * from "+table, con, parse_dates = ['TimeStep'])
    df.columns=columns
    con.close()
    df = df.sort_index()
    df = df[use_columns]
    fig, ax = plt.subplots()
    df.plot(ax=ax, x='TimeStep', legend=False)
    ax.set_xlabel('')
    ax.set_title(title)
    ax.set_ylim(-.5,.5)
    plotly_fig = tls.mpl_to_plotly(fig)
    plotly_fig['layout']['plot_bgcolor'] = "rgb(213, 226, 233)"
    plotly_fig['layout']['xaxis']['gridcolor'] = "white"
    plotly_fig['layout']['yaxis']['gridcolor'] = "white"
    plotly_fig['layout']['xaxis']['ticks'] = ""
    plotly_fig['layout']['yaxis']['range'] = limits
    plotly_fig['layout']['yaxis']['title'] = ylabel
    plotly_fig['layout']['autosize'] = True
    plotly_fig['layout']['showlegend'] = True
    print dir(plotly_fig.layout)
    
    if online==False:
        plotly.offline.plot(plotly_fig, filename=file_name)
    if online==True:    
        py.plot(plotly_fig, filename=file_name, fileopt='overwrite')
Example #3
0
def create_user_station_contrib_bar_graph():

    plotlyTraces = []

    if os.path.exists('../data/contributionTotals.csv'):
        totalfile = open('../data/contributionTotals.csv', 'r')
        totalreader = csv.reader(totalfile, delimiter=',')
        firstrow = True
        for user in totalreader:
            if not firstrow:
                # Parse the contribution dict column
                contribution_dict_str = user[4].replace("-", ",").replace("\'", "\"")
                contribution_dict = json.loads(contribution_dict_str)
                if len(contribution_dict_str) > 2: #If there is at least one contribution
                    plotlyTraces.append(go.Bar(
                        x=list(contribution_dict.keys()),
                        y=list(contribution_dict.values()),
                        name=user[0]))
            firstrow = False
        totalfile.close()

    layout = go.Layout(
        barmode='stack'
    )

    fig = go.Figure(data=plotlyTraces, layout=layout)
    py.plot(fig, filename='stacked-bar')
Example #4
0
def plot_scatter(x_axis, y_axis, xax_name, yax_name, title):
    """
    Plots a scatterplot of given input lists with axes labels
    
    Parameters:
        x_axis: a list that represents x-values        
        y_axis: a list that represents y-values  
        xax_name: a string for x-axis title
        yax_name: a string for y-axis title
        title: a string for title of plot and plotly page
        
    Returns None
    """
    # Data features
    trace = go.Scatter(
        x = x_axis,
        y = y_axis,
        mode = 'markers',
        marker = dict(
            size = 20,
            color = y_axis)
    )
    data = [trace]
    
    # Layout of plot
    layout = go.Layout(
        dict(title = title,
        xaxis = dict(title = xax_name),
        yaxis = dict(title = yax_name))
    )
       
    # Plots figure in browser using Plotly            
    fig = dict(data = data, layout = layout)
    py.plot(fig, filename = title)   
Example #5
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)))
Example #6
0
    def plot(self):
        for j, k in self.word_count_list:
            self.words.append(j)
            self.counts.append(k)

        trace_bar1 = go.Bar(
            x=self.counts,
            y=self.words,
            orientation='h',
            marker=go.Marker(color='#E3BA22'))

        # Make Data object
        self.data = go.Data([trace_bar1])

        self.title = 'Word Frequency'  # plot's title

        # Make Layout object
        self.layout = go.Layout(
            title=self.title,       # set plot title
            showlegend=False,  # remove legend
            orientation = 'h',
            yaxis= go.YAxis(
            title='Words', # y-axis title
            # range=[-15.5,25.5],              # set range
            zeroline=False,                  # remove thick line at y=0
            gridcolor='white'                # set grid color to white
            ),
            paper_bgcolor='rgb(233,233,233)',  # set paper (outside plot)
            plot_bgcolor='rgb(233,233,233)',   #   and plot color to grey
            )
                # Make Figure object
        self.fig = go.Figure(data=self.data, layout=self.layout)

        # (@) Send to Plotly and show in notebook
        py.plot(self.fig, filename='CITA-Bar-Graph')
    def graph(self):

        stream_randomizer = Scatter(
            x=[],
            y=[],
            stream=dict(
                token=self.streamtoken,
            )
        )

        layout = Layout(
            title="IoTPy Randomizer"
        )

        this = Figure(data=[stream_randomizer], layout=layout)
        py.plot(this, filename='IotPy Randomizer', auto_open=False)

        stream = py.Stream(self.streamtoken)
        stream.open()
        time.sleep(5)

        counter = 0

        while True:
            randomizerdata = randint(0,100)
            stream.write({'x': counter, 'y': randomizerdata})
            counter += 1
            time.sleep(0.25)
Example #8
0
def main():
  py.sign_in('JDGrillo', 'ymn6lb95az')
  trace = go.Scatter(
    x = [1991,1992,1993,1994],
    y = [2,4,3,9],
    mode = 'markers'
	)
  data = [trace]
  layout = go.Layout(
    xaxis=dict(
	  title="X-Axis",
      titlefont=dict(
        family='Arial, sans-serif',
        size = 18,
        color='grey'
		),
      showexponent='All'
    ),
	yaxis=dict(
      title="Y-Axis",
      titlefont=dict(
        family='Arial, sans-serif',
        size = 18,
        color='lightgrey'
		),
      showexponent='All'
    )
	
    )
  pplot = go.Figure(data = data, layout=layout)	
  py.plot(pplot,filename= 'scatter')
Example #9
0
def plot_sgd(x,y, name = "SGD"):
	import plotly.plotly as py
	import plotly.graph_objs as go
	data = [go.Scatter(x = x, y = y, name = name)]
	layout = go.Layout(xaxis = dict(type = 'log', autorange = True),yaxis = dict(autorange=True))
	fig = go.Figure(data = data, layout = layout)
	py.plot(fig,filename = name)	
Example #10
0
def create_hour_like_heatmap(posts):
	times=[]
	for i in range(24): #add 24 hours to the times list
		times.append({"hour": + i, "likes": 0, "posts": 0})
	for post in posts: #loop through the posts
		for time in times: #loop through the times
			if post['time'].hour==time['hour']: #if the times are equal for the current post's time and the current loop's time:
				time['likes']+=post['likes']
				time['posts']+=1
				break #if we've found a match, break, since we already found the hour in times and we don't need to keep searching for it

	for time in times: #get the average number of likes
		if not time['posts']==0:
			time['avg_likes']=float(time['likes'])/time['posts']
		else: #to prevent division by 0
			time['avg_likes']=0

	data=[
		go.Heatmap(
			x=[time['hour'] for time in times],
			y=["Likes"]*24,
			z=[time['avg_likes'] for time in times]
		)
	]

	layout=go.Layout(
		title="Aces Nation Average Likes By Hour",
		xaxis=dict(
			title="Hour",
		)
	)

	fig=dict(data=data, layout=layout)
	plotly.plot(fig)
def dataPlotlyHandler():

    py.sign_in(username, api_key)

    trace1 = Scatter(
        x=[],
        y=[],
        stream=dict(
            token=stream_token,
            maxpoints=200
        )
    )

    layout = Layout(
        title='Hello Internet of Things 101 Data'
    )

    fig = Figure(data=[trace1], layout=layout)

    print py.plot(fig, filename='Hello Internet of Things 101 Plotly')

    i = 0
    stream = py.Stream(stream_token)
    stream.open()

    while True:
        stream_data = dataPlotly()
        stream.write({'x': i, 'y': stream_data})
        i += 1
        time.sleep(0.25)
Example #12
0
def interval_by_hour(timeslice_dict, chartname="interval_by_hour.html"):
    datas = []
    for num in range(0, 24):
        h = str(num)
        timeh = "time"+h
        if timeh in timeslice_dict:
            x = []
            print "t", h, timeslice_dict[timeh]
            for i in timeslice_dict[timeh]:
                x.append(h)
            print x
            trace = Scatter(
                x=x,
                y=timeslice_dict[timeh],
                mode="markers",
                name=timeh
            )
            datas.append(trace)
    data = Data(datas)
    layout = Layout(
        xaxis = dict(title="hours"),
        yaxis = dict(title="interval")
    )
    fig = Figure(data=data, layout=layout)

    py.plot(fig, filename=chartname)
Example #13
0
def interval_count_until_noti(list_run, chartname="interval_count_until_noti.html"):
    datas = []

    dict_by_appname = dict()
    for rows in list_run:
        name = rows[stdtable.DICT_APPNAME]
        if name in dict_by_appname:
            dict_by_appname[name].append([rows[stdtable.DICT_INTERVAL], rows[stdtable.DICT_NOTI_COUNT]])
        else:
            dict_by_appname[name] = [[rows[stdtable.DICT_INTERVAL], rows[stdtable.DICT_NOTI_COUNT]]]

    for name in dict_by_appname:
        x = []
        y = []
        print name, dict_by_appname[name]
        for rows in dict_by_appname[name]:
            x.append(rows[1])
            y.append(rows[0])
        trace = Scatter(
            x=x,
            y=y,
            mode="markers",
            name=name
        )
        datas.append(trace)
    data = Data(datas)

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

    py.plot(fig, filename=chartname)
Example #14
0
def datagen(t, pmax, step):
    while (t < pmax):
         S1 = (2/3)*cos((sqrt(3)*t)/2)*e**(t/2) + 1/(3*e**t)
         S2 = (1/3*cos(sqrt(3)/2*t)+(1/sqrt(3))*sin((sqrt(3)/2)*t))*e**(t/2) + (-1)/(3*e**t)
         S3 = (-1/3*cos(sqrt(3)/2*t)+(1/sqrt(3))*sin((sqrt(3)/2)*t))*e**(t/2) + 1/(3*e**t)
         t = t + step

         value = S1, S2, S3
         ss0 = pd.Series(S1, index=s0.append(S1))
         ss1 = pd.Series(S2, index=s1.append(S2))
         ss2 = pd.Series(S3, index=s2.append(S3))

#         p0s = str(s0)
#         p1s = str(s1)
#         p2s = str(s2)

#   print(p0s + ", " + p1s + ", " + p2s)
#   print(str(ss0) + ", " + str(ss1) + ", " + str(ss2))
    print("Plottable data has been generated.")

    trace1 = go.Scatter3d(  x=s0,
                            y=s1,
                            z=s2
                            )
    Data = [trace1]
    Layout = go.Layout(
        title='S3 Spiral Plot'
    )
    fig = go.Figure(data=Data, layout=Layout)
    py.plot(fig, filename='')
 def show_plot(self):
     plot_trace = graph_objs.Scatter(
         x=self.x,
         y=numpy.subtract(self.y,self.base),
         mode='lines',
         name='Original Plot',
     )
     maximums_trace = graph_objs.Scatter(
         x=[self.x[i] for i in self.indices],
         y=[self.y[j]-self.base[j] for j in self.indices],
         mode='markers',
         marker=dict(
             size=8,
             color='rgb(255,0,0)',
             symbol='cross'
         ),
         name='Detected Maximums'
     )
     minimums_trace = graph_objs.Scatter(
         x=[self.x[i] for i in self.min_indices],
         y=[self.y[j]-self.base[j] for j in self.min_indices],
         mode='markers',
         marker=dict(
             size=8,
             color='rgb(0,0,255)',
             symbol='cross'
         ),
         name='Detected Minimums'
     )
     data = [plot_trace, maximums_trace, minimums_trace]
     plotly.plot(data, filename='psc')
Example #16
0
	def test_vline_text(self):
		self.data.append(AxVline(5, self.yy2, text = 'vertical label').data)

		data = Data(self.data)
		figure = Figure(data = data)

		py.plot(figure, filename = 'carpet_plot/axvline_test_2', overwrite = True)
Example #17
0
    def __init__(self, title):
        self.title = title
        self.directorycurrent = os.path.dirname(os.path.realpath(__file__))
        self.directoryconfiguration = self.directorycurrent + '/../configuration/'
        self.configuration = ConfigParser.ConfigParser()
        self.credentialspath = self.directoryconfiguration + "credentials.config"
        self.configuration.read(self.credentialspath)
        self.username = self.configuration.get('plotly','username')
        self.apikey = self.configuration.get('plotly','apikey')
        self.streamtoken = self.configuration.get('plotly','streamtoken')

        py.sign_in(self.username, self.apikey)

        stream_data = Scatter(
            x=[],
            y=[],
            stream=dict(
                token=self.streamtoken,
            )
        )

        layout = Layout(
            title = self.title
        )

        this = Figure(data=[stream_data], layout=layout)
        py.plot(this, filename=self.title, auto_open=False)

        self.stream = py.Stream(self.streamtoken)
        self.stream.open()
        time.sleep(5)
Example #18
0
	def test_hline_with_new_linestyle(self):
		self.data.append(AxHline(50, self.xx, text = "Sample line", line = Line(color = 'grey', dash = 'dashed')).data)

		data = Data(self.data)
		figure = Figure(data = data)

		py.plot(figure, filename = 'carpet_plot/axhline_test_3', overwrite = True)
Example #19
0
	def test_basic_vline(self):
		self.data.append(AxVline(5, self.yy2).data)

		data = Data(self.data)
		figure = Figure(data = data)

		py.plot(figure, filename = 'carpet_plot/axvline_test_1', overwrite = True)
Example #20
0
	def test_basic_hline(self):
		self.data.append(AxHline(50, self.xx).data)

		data = Data(self.data)
		figure = Figure(data = data)

		py.plot(figure, filename = 'carpet_plot/axhline_test_1', overwrite = True)
Example #21
0
	def test_basic_hline_with_text(self):
		self.data.append(AxHline(50, self.xx, text = "Sample line").data)

		data = Data(self.data)
		figure = Figure(data = data)

		py.plot(figure, filename = 'carpet_plot/axhline_test_2', overwrite = True)
Example #22
0
def rmsdist_histos():
    """#different/similar vs rms_dist"""
    out_fig = Figure()
    inmatdb_df = read_csv('mpworks/check_snl/results/bad_snlgroups_2_in_matdb.csv')
    inmatdb_df_view = inmatdb_df.loc[inmatdb_df['category']=='diff. SGs']
    different = inmatdb_df_view.loc[inmatdb_df_view['scenario']=='different']
    similar = inmatdb_df_view.loc[inmatdb_df_view['scenario']=='similar']

    def rmsdist(tupstr):
        if isinstance(tupstr, float) and math.isnan(tupstr): return None
        tup = map(float, tupstr[1:-1].split(','))
        return math.sqrt(tup[0]*tup[0]+tup[1]*tup[1])

    different_rmsdist = filter(None, map(rmsdist, different['rms_dist']))
    similar_rmsdist = filter(None, map(rmsdist, similar['rms_dist']))
    different_trace = Histogram(x=different_rmsdist, name='different', opacity=0.75)
    similar_trace = Histogram(x=similar_rmsdist, name='similar', opacity=0.75)
    out_fig['data'] = Data([different_trace,similar_trace])
    out_fig['layout'] = Layout(
        title='rms_dist of different/similar matching SNLs w/ different SGs',
        xaxis=XAxis(showgrid=False, title='sqrt(rms_dist)'),
        barmode='overlay'
    )
    filename = 'canonicals_rmsdist_'
    filename += datetime.datetime.now().strftime('%Y-%m-%d') 
    py.plot(out_fig, filename=filename, auto_open=False)
    py.image.save_as(out_fig, 'canonicals_rmsdist.png')
Example #23
0
def sg1_vs_sg2_plotly():
    """plot SG #1 vs #2 via plotly"""
    out_fig = Figure()
    bisectrix = Scatter(x=[0,230], y=[0,230], mode='lines', name='bisectrix', showlegend=False)
    inmatdb_df = read_csv('mpworks/check_snl/results/bad_snlgroups_2_in_matdb.csv')
    inmatdb_text = map(','.join, zip(
        inmatdb_df['task_id 1'], inmatdb_df['task_id 2']
    ))
    inmatdb_trace = Scatter(
        x=inmatdb_df['sg_num 2'].as_matrix(), y=inmatdb_df['sg_num 1'].as_matrix(),
        text=inmatdb_text, mode='markers', name='in MatDB'
    )
    notinmatdb_df = read_csv('mpworks/check_snl/results/bad_snlgroups_2_notin_matdb.csv')
    notinmatdb_text = map(','.join, zip(
        map(str, notinmatdb_df['snlgroup_id 1']), map(str, notinmatdb_df['snlgroup_id 2'])
    ))
    notinmatdb_trace = Scatter(
        x=notinmatdb_df['sg_num 2'].as_matrix()+0.1,
        y=notinmatdb_df['sg_num 1'].as_matrix()+0.1,
        text=notinmatdb_text, mode='markers', name='not in MatDB'
    )
    out_fig['data'] = Data([bisectrix, notinmatdb_trace, inmatdb_trace])
    out_fig['layout'] = Layout(
        hovermode='closest',
        title='Spacegroup Assignment Comparison of matching Canonical SNLs',
        xaxis=XAxis(showgrid=False, title='SG #2', range=[0,230]),
        yaxis=YAxis(showgrid=False, title='SG #1', range=[0,230]),
    )
    filename = 'spacegroup_canonicals_'
    filename += datetime.datetime.now().strftime('%Y-%m-%d') 
    py.plot(out_fig, filename=filename, auto_open=False)
    py.image.save_as(out_fig, 'canonicals_spacegroups.png')
Example #24
0
def plot_POS_pred_results(results, results_b, tuple_size, num_trials, name):
    marker_scale = 100/num_trials
    trace1 = go.Scatter(
        x=results[0],
        y=results[1],
        mode='lines+markers',
        hoverinfo='text',
        name='pos',
        marker=dict(size=[n*marker_scale for n in results[2]], opacity=0.5),
        text=['Precision: {}<br>Count: {}'.format(p, c) for (p, c) in
              zip([round(n, 2) for n in results[1]], results[2])]
    )
    trace2 = go.Scatter(
        x=results_b[0],
        y=results_b[1],
        mode='lines+markers',
        hoverinfo='text',
        name='pos_buckets',
        marker=dict(size=[n*marker_scale for n in results_b[2]], opacity=0.5),
        text=['Precision: {}<br>Count: {}'.format(p, c) for (p, c) in
              zip([round(n, 2) for n in results_b[1]], results_b[2])]
    )
    data = [trace1, trace2]
    layout = go.Layout(
        title='POS Prediction Precision ({}-tuple, n={}, text={})'.format(
            tuple_size, num_trials, name),
        xaxis=dict(title='Delta Threshold'),
        yaxis=dict(title='Precision'),
        showlegend=False
    )
    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename='pos-prediction-delta-threshold'+name+str(tuple_size))
Example #25
0
def create_plot(number_of_epochs_completed, y_train_loss_line_list, y_val_loss_line_list, name_of_plot):
	try:
		x_axis = np.linspace(1,number_of_epochs_completed, number_of_epochs_completed)
		y_train_loss_line = np.asarray(y_train_loss_line_list)
		y_val_loss_line = np.asarray(y_val_loss_line_list)


		tracetrainloss = go.Scatter(
			x = x_axis,
			y = y_train_loss_line,
			name = 'Training Loss',
			line = dict(
				color = ('rgb(205, 12, 24)'),
				width = 3)
		)

		tracevalloss = go.Scatter(
			x = x_axis,
			y = y_val_loss_line,
			name = 'Validation Loss',
			line = dict(
				color = ('rgb(22, 96, 167)'),
				width = 3)
		)


		data = [tracetrainloss, tracevalloss]
		py.plot(data, filename=name_of_plot , auto_open=False)
	except:
		traceback.print_exc()
		pass
    def languageStats(self, database):
        reducer = Code("""function(obj, prev){
                        prev.count++;
                    }""")
        results = database.group(key={"Language":""}, condition="", initial={"count": 0}, reduce=reducer)
        base = list()
        values = list()
        for doc in results:
            base.append(doc['Language'])
            values.append(doc['count'])

        data = [
            go.Bar(
                x = base,
                y = values
            )
        ]
        plot_url = plt.plot(data, filename='LanguageStats')
        print plot_url

        base.pop(0)
        values.pop(0)

        data = [
            go.Bar(
                x=base,
                y=values
            )
        ]
        plot_url = plt.plot(data, filename='LanguageStatsWithoutEnglish')

        print plot_url
Example #27
0
    def paint_PAA(self, data_nomalize, data_PAA):
        data_time_1 = []
        data_time_2 = []
        tmp = 0
        for i in range(len(data_PAA)):
            data_time_2.append(tmp)
            for j in range(self.w):
                data_time_1.append(tmp)
                tmp += 1

        # matplotlib paint
        '''plt.plot(data_nomalize, 'g--', data_PAA_, 'b-')
        plt.show()'''

        # plotly paint
        data1 = {'x': data_time_1, 'y': data_nomalize}
        trace1 = Scatter(
            data1,
            mode='lines',
            marker=Marker(
                color='blue',
                symbol='square'))

        data2 = {'x': data_time_2, 'y': data_PAA}
        trace2 = Scatter(
            data2,
            mode='lines',
            marker=Marker(
                color='green',
                symbol='square'))

        data = Data([trace1, trace2])
        py.plot(data)
Example #28
0
def create_heroes_dmg_cost_graphs():
    heroes_data = read_heroes_dmg_cost_data('./Output/Heroes_Dmg_Cost')
    plotly.sign_in("haukurpalljonsson", "dr78f5q3yh")
    dps_data = []
    dps_data_total = []
    for x in range(1, len(heroes_data) + 1):
        axis_levels = []
        axis_dps_increase = []
        axis_dps_increase_total = []
        hero_key = str(x)
        #I know (has to be fixed) that the first level inserted is 1
        for y in range(1, int(len(heroes_data[hero_key])/2) + 1):
            level_key = str(y)
            level_key_total = str(y) + '+'
            axis_levels.insert(y-1, y)
            axis_dps_increase.insert(y-1, int(heroes_data[hero_key][level_key][1]))
            axis_dps_increase_total.insert(y-1, int(heroes_data[hero_key][level_key_total][1]))

        #moa

        dps_trace = Scatter(x=axis_levels, y=axis_dps_increase)
        dps_data.append(dps_trace)
        dps_trace_total = Scatter(x=axis_levels, y=axis_dps_increase_total)
        dps_data_total.append(dps_trace_total)

    print(plotly.plot(dps_data, filename='dps_increase'))
    print(plotly.plot(dps_data_total, filename='dps_increase_total'))
Example #29
0
def plot(stats_dic):
    """Given a dictionary generated by stats_master, connects to plot.ly and
    generates a bar graph representing the frequency of searched key words."""
    new_dic = separate_stats(stats_dic)
    comment_dic = (new_dic[0])
    thread_dic = (new_dic[1])

    data_comments = go.Bar(
                x=['/r/'+key[0] for key in comment_dic],
                y=[count[1][1]/float(count[1][0]) for count in comment_dic],
                name='Comments'
            )
    data_threads = go.Bar(
                x=['/r/'+key[0] for key in comment_dic],
                y=[count[1][1]/float(count[1][0]) for count in thread_dic],
                name='Threads'
            )

    data = [data_comments, data_threads]

    layout = go.Layout(
        barmode='stack',
        title='Percentage of posts containing keywords',
        xaxis=dict(
            title='Subreddit'
        ),
        yaxis=dict(
            title='Percentage'
        )
    )

    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename='comment-bar')

    return 0
Example #30
0
def plot_city_bar(input_dict, xax_name, yax_name, title):
    """
    Makes a bar graph of given input dictionary with axes labels
    
    Parameters:
        input_dict: a dictionary mapping strings to numbers
        xax_name: a string for x-axis title
        yax_name: a string for y-axis title
        title: a string for title of plot and plotly page
        
    Returns None
    """
    # Data features
    data = [
        go.Bar(
            x = input_dict.keys(),
            y = input_dict.values(),
            opacity = 0.8,
            name = title,
            marker = dict(color = input_dict.values())
        )
    ]
    
    # Layout of plot
    layout = go.Layout(
        title = title,
        xaxis = dict(title = xax_name),
        yaxis = dict(title = yax_name)
    )
    
    # Plots figure to browser using Plotly
    fig = go.Figure(data = data, layout = layout)
    py.plot(fig, filename = title) 
from funciones import gcl_uniforme
import constante

# Paso 1: Generamos muestras de la variable uniforme U
x_n = constante.SEMILLA
u = []  # array de uniformes
x = []  # array de inversas

for _ in range(constante.CANT_EXPERIMENTOS):
    x_n = gcl_uniforme(x_n)
    u.append(x_n)

#  Paso 2: Aplicar la transformacion inversa
paramLambda = float(1) / float(15)
for i in range(len(u)):
    x.append(-log(1 - u[i]) / paramLambda)  # Transformacion inversa

# Mostramos histograma del resultado
data = [go.Histogram(x=x)]
py.plot(data, filename='histograma-inversa-exponencial')

# Mostramos media, varianza y moda muestrales y teoricos
media = np.mean(x)
varianza = np.var(x)
moda = max(set(x), key=x.count)

print("Media muestral: {0} Varianza muestral: {1} Moda muestral: {2}".format(
    media, varianza, moda))
print("Media teorica:  {0} Varianza teorica:  {1} Moda teorica:  {2}".format(
    15, 15 * 15, 0))
Example #32
0
def test_plot_from_grid():
    g = upload_and_return_grid()
    url = py.plot([Scatter(xsrc=g[0], ysrc=g[1])],
                  auto_open=False, filename='plot from grid')
    return url, g
Example #33
0
def plot(yaxis_values, positions, yaxis_title,
         xaxis_title, plot_title, box_name):
    """
    Plot nba data

    :ages: list of the ages of players
    :positions: list of the positions
    :yaxis_title: title of the yaxis
    :xaxis_title: title of the xaxis
    :plot_title: title of the plot
    :box_name: name of the box

    :return:  None, data sent to plotly via API
    """
    data = Data([
        Box(
            y=yaxis_values,
            x=positions,
            name=box_name,
            boxmean=True,
            boxpoints='all',
            jitter=0.5,
            whiskerwidth=0.5,
            fillcolor='rgb(106, 168, 79)',
            marker=Marker(
                color='rgba(7, 55, 99, 0.5)',
                size=4,
                symbol='circle',
                opacity=0.7
            ),
            line=Line(
                color='rgba(7, 55, 99, 0.5)',
                width=2
            ),
            opacity=1,
            showlegend=False
        )
    ])
    layout = Layout(
        title=plot_title,
        showlegend=False,
        autosize=True,
        width=792,
        height=469,
        xaxis=XAxis(
            title=xaxis_title,
            range=[-0.6799999999999999, 6.5],
            type='category',
            autorange=True,
            showexponent='all',
            side='bottom'
        ),
        yaxis=YAxis(
            title=yaxis_title,
            range=[17.944444444444443, 39.05555555555556],
            type='linear',
            autorange=True,
            showexponent='all'
        ),
        paper_bgcolor='rgb(255, 255, 255)',
        plot_bgcolor='rgb(217, 217, 217)',
        hovermode='closest',
        boxmode='overlay',
        boxgap=0.4,
        boxgroupgap=0.4
    )
    fig = Figure(data=data, layout=layout)
    py.plot(fig)
Example #34
0
def function():
    mapbox_access_token = 'pk.eyJ1IjoiY2xlaXR1cyIsImEiOiJjamgwZ2c1a3Yxc3dtMnFtb2ptdDR5ZWs0In0.sjZdn45v32AojmWGWIN9Tg'
    pt.set_credentials_file(username='******', api_key='9LICBZ681YiPTiSZCuFX')

    # ########################### Reading Initial Data ###################################
    with open('fb_nodes.json') as f:
        nodes = json.load(f)

    with open('fb_edges.json') as f:
        links = json.load(f)

    for i in links:
        i['value'] = 'init'

    # ########################### Reading Initial Data ###################################

    #nodes = data['nodes']
    #links = data['edges']

    M = nx.Graph()

    M = nx.Graph(
        [(i['source'], i['target'], {'value': i['value']}) for i in links])
    for i in range(len(M.nodes)):
        node = nodes[i]['id']
        M.add_node(node, group=nodes[i]['group'])
        M.add_node(node, name=nodes[i]['name'])
        M.add_node(node, istrain=nodes[i]['istrain'])
        M.add_node(node, lat=nodes[i]['lat'])
        M.add_node(node, lon=nodes[i]['lon'])
        M.add_node(node, id=nodes[i]['id'])


    # ###################### Evolution ####################


    # Common Neighbors
    CN = [(e[0], e[1], len(list(nx.common_neighbors(M, e[0], e[1]))))
          for e in nx.non_edges(M)]
    CN.sort(key=operator.itemgetter(2), reverse=True)

    # Jaccard coef
    jaccard = list(nx.jaccard_coefficient(M))
    jaccard.sort(key=operator.itemgetter(2), reverse=True)

    # Resource Allocation index
    RA = list(nx.resource_allocation_index(M))
    RA.sort(key=operator.itemgetter(2), reverse=True)

    # Adamic-Adar index
    AA = list(nx.adamic_adar_index(M))
    AA.sort(key=operator.itemgetter(2), reverse=True)

    # Preferential Attachement
    PA = list(nx.preferential_attachment(M))
    PA.sort(key=operator.itemgetter(2), reverse=True)

    # ###################### Prediction on Future Edge Linkage ####################

    FM = M
    for i in PA[0:int(0.1*len(M.edges()))]:
        FM.add_edge(i[0], i[1], value='new')

    for i in CN[0:int(0.1*len(M.edges()))]:
        FM.add_edge(i[0], i[1], value='new')

    #Layout
    pos=nx.fruchterman_reingold_layout(FM, dim=3)
    lay=list()
    for i in pos.values():
        lay.append(list(i))
    N = len(FM.nodes())
    
    ulti = {}
    for i in pos.keys():
        ulti[i]=list(pos[i])

    #Eigenvector centrality criteria (normalised)
    Geigen=nx.eigenvector_centrality(FM)
    for i in Geigen:
        ulti[i].append(float(Geigen[i])/max(Geigen.values()))

    #Closeness centrality
    Gclose=nx.closeness_centrality(FM)
    for i in Gclose:
        ulti[i].append(Gclose[i])

    #Betweeness centrality
    Gbetween=nx.betweenness_centrality(FM)
    for i in Gbetween:
        ulti[i].append(Gbetween[i])

    # ###################### Plot ####################

    # Nodes and Edges coordinates
    Xv=[lay[k][0] for k in range(N)]# x-coordinates of nodes
    Yv=[lay[k][1] for k in range(N)]# y-coordinates
    Zv=[lay[k][2] for k in range(N)]# z-coordinates
    Xed = []
    Yed = []
    Zed = []
    Xned = []
    Yned = []
    Zned = []
    for edge in M.edges():
        Xed+=[pos[edge[0]][0],pos[edge[1]][0], None]
        Yed+=[pos[edge[0]][1],pos[edge[1]][1], None]
        Zed+=[pos[edge[0]][2],pos[edge[1]][2], None]

    for edge in [(i[0], i[1]) for i in list(FM.edges(data=True)) if i[2]['value'] == 'new']:
        Xned+=[pos[edge[0]][0],pos[edge[1]][0], None]
        Yned+=[pos[edge[0]][1],pos[edge[1]][1], None]
        Zned+=[pos[edge[0]][2],pos[edge[1]][2], None]


    trace1=Scatter3d(x=Xed,
                   y=Yed,
                   z=Zed,
                   mode='lines',
                   line=Line(color='rgb(125,125,125)', width=1),
                   hoverinfo='none'
                   )

    trace2=Scatter3d(x=Xv,
                   y=Yv,
                   z=Zv,
                   mode='markers',
                   name='actors',
                   marker=Marker(symbol='dot',
                                 color=[i[-3] for i in ulti.values()], # Eigenvector centrality
							     #color=[i[-2] for i in ulti.values()], # Closeness centrality
							     #color=[i[-1] for i in ulti.values()], # Betweeness centrality
                                 #color=[data['nodes'][k]['group'] for k in range(len(data['nodes']))], #

                                 size=6,colorbar=ColorBar(
                    title=''
                ),
                                 colorscale='Viridis',
                                 line=Line(color='rgb(158,18,130)', width=0.5)
                                 ),
                   text=ulti.keys(),  # node Labels
                   hoverinfo='text'
                   )

    data=Data([trace1, trace2])
    py.plot(data, filename = 'fb-3d')
    return
Example #35
0
#Setting Predictors and Target Values
features_data = trainData[:, 0:4]
target_data = trainData[:, 4]

# Plotting the graph
xd = trainData[:, 2]
yd = trainData[:, 4]
layout = dict(
    title='Average Open and Volumes of Shares',
    xaxis=dict(title='Open'),
    yaxis=dict(title='Volume'),
)
trace = go.Scatter(x=xd, y=yd, mode='markers')
data = [trace]
py.plot(data, layout)

#Tuning Predictors with the Pytorch datatype
predictors = torch.from_numpy(np.array(features_data)).float()
predictors = Variable(predictors)

outputData = torch.from_numpy(np.array(target_data)).float()
outputData = Variable(outputData)

#Perfomring Linear Regression on the training dataset
linearRegression = nn.Linear(4, 1)

criterion = nn.MSELoss()
optimizer = optim.Adam(linearRegression.parameters(), lr=LEARNING_RATE)

#Running the loop for 1000 times to findout the best accuracy result
Example #36
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])
    fig = Figure(data=data, layout=layout)
    py.plot(fig, filename='Sample Code For History Of Clients ')
Example #37
0
    def plotly_gantt(self, best_solution):
        '''Generating and uploading gantt chart data'''
        j_keys = best_solution['num_lot'].unique()
        # m_keys = best_solution['machine'].unique()
        gantt_dataframe = []

        # Adding extention gene code
        best_solution = FitnessCalculation.adding_gene_code(
            self, best_solution)
        # Calculate each gene completion time
        best_solution['processing_time'] = best_solution.apply(
            lambda row: FitnessCalculation.calculate_job_processing_time(
                self, row.part, row.operation, row.num_sequence),
            axis=1)
        best_solution['processing_time_plus'] = best_solution.apply(
            lambda row: FitnessCalculation.calculate_job_processing_time_plus(
                self, row.processing_time, row.machine, row.num_lot,
                best_solution),
            axis=1)

        # Calculate each gene completion time
        best_solution = FitnessCalculation.calculate_completion_time(
            self, best_solution.index.tolist(), best_solution)

        # Convert start time & completion time to UTC time
        best_solution['calendar_completion_time'] = best_solution.apply(
            lambda row: DataOutput.calculate_calendar_completion_time(
                self, row),
            axis=1)
        best_solution['calendar_start_time'] = best_solution.apply(
            lambda row: DataOutput.calculate_calendar_start_time(self, row),
            axis=1)
        #Slice the raw to the final report
        best_solution = best_solution[[
            'num_job', 'num_lot', 'part', 'operation', 'machine',
            'num_sequence', 'lotsize_assign', 'processing_time',
            'processing_time_plus', 'calendar_start_time',
            'calendar_completion_time'
        ]]

        for _, row in best_solution.iterrows():
            num_job = row['num_job']
            machine = row['machine']
            gantt_finish = row['calendar_completion_time']

            gantt_start = row['calendar_start_time']

            gantt_dataframe.append(
                dict(Task='Machine %s' % (machine),
                     Start='%s' % (str(gantt_start)),
                     Finish='%s' % (str(gantt_finish)),
                     Resource='Job_%s' % (num_job)))

        color = {
            'Job_%s' % (k):
            'rgb' + str(tuple(np.random.choice(range(256), size=3)))
            for k in range(len(j_keys))
        }
        fig = ff.create_gantt(gantt_dataframe,
                              index_col='Resource',
                              colors=color,
                              show_colorbar=True,
                              group_tasks=True,
                              showgrid_x=True,
                              title='LN Wedge Lot Scheduling')
        return py.plot(fig,
                       filename='LN Wedge Lot Scheduling',
                       world_readable=True)
def volunteer_population_region_command(input_4):

    ## 4.)	Bar graph that displays the current volunteer population of world regions.

    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    selector = "SELECT C.Region, C.CurrentVolunteers "
    fromer = "FROM Countries AS C "
    orderer = "ORDER BY C.CurrentVolunteers DESC"
    limiter = ""
    joiner = ""
    wherer = ""

    statement = selector + fromer + joiner + wherer + orderer + limiter
    cur.execute(statement)
    data = cur.fetchall()
    conn.close()

    Europe = 0
    Africa = 0
    Americas = 0
    Asia = 0
    Oceania = 0

    for region in data:
        if region[0] == "Europe":
            Europe += region[1]
        elif region[0] == "Africa":
            Africa += region[1]
        elif region[0] == "Americas":
            Americas += region[1]
        elif region[0] == "Asia":
            Asia += region[1]
        elif region[0] == "Oceania":
            Oceania += region[1]
        else:
            pass

    region_tuples = [("Europe", Europe), ("Africa", Africa),
                     ("Americas", Americas), ("Asia", Asia),
                     ("Oceania", Oceania)]

    regions = []
    volunteers = []

    for tupe in region_tuples:
        regions.append(tupe[0])
        volunteers.append(tupe[1])

    trace0 = go.Bar(x=regions,
                    y=volunteers,
                    text=regions,
                    marker=dict(color='rgb(158,202,225)',
                                line=dict(
                                    color='rgb(8,48,107)',
                                    width=1.5,
                                )),
                    opacity=0.6)

    data = [trace0]
    layout = go.Layout(title='Current Volunteers by Region', )

    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename='text-hover-bar')
def map_command(input_1):

    ## World Map Scatter Plot that displays a point for each Peace Corps country with a hover caption that displays number of current volunteers and the languages they speak.

    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    selector = "SELECT C.Name, C.CurrentVolunteers, C.Coordinates "
    fromer = "FROM Countries AS C"
    orderer = ""
    limiter = ""
    joiner = ""
    wherer = ""

    statement = selector + fromer + joiner + wherer + orderer + limiter
    cur.execute(statement)
    data = cur.fetchall()
    conn.close()

    coords_tuples = []

    for country in data:
        coords = country[2].strip().split(",")
        coord_tuple = (float(coords[0]), float(coords[1]), country[0],
                       int(country[1]))
        coords_tuples.append(coord_tuple)

    lat_vals = []
    lon_vals = []
    country_names = []
    country_volunteers = []

    for tupe in coords_tuples:
        if tupe[0] != "":
            lat_vals.append(tupe[0])
            lon_vals.append(tupe[1])
            country_names.append(tupe[2])
            country_volunteers.append(tupe[3])

    data = [ dict(
           type = 'choropleth',
           locations = country_names,
           locationmode = "country names",
           z = country_volunteers,
           text = 'Current Volunteers',
           colorscale = [[0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
               [0.6,"rgb(90, 120, 245)"],[0.7,"rgb(106, 137, 247)"],[1,"rgb(220, 220, 220)"]],
           autocolorscale = False,
           reversescale = True,
           marker = dict(
               line = dict (
                   color = 'rgb(180,180,180)',
                   width = 0.5
               ) ),
           colorbar = dict(
               autotick = False,
               tickprefix = '',
               title = 'Current Volunteers'),
         ) ]

    layout = dict(
        title='Current Volunteers Serving in Peace Corps Countries<br>Source:\
            <a href="https://www.peacecorps.gov/countries/">\
            Peace Corps Countries</a>',
        geo=dict(showframe=False,
                 showcoastlines=False,
                 projection=dict(type='Mercator')))

    fig = dict(data=data, layout=layout)
    py.plot(fig, validate=False, filename='d3-world-map')
def plotlyslider(date,Y1,Y2,name1='1',name2='2',\
                 TITLE='Time Series with Rangeslider'):

    trace_1 = go.Scatter(
            x=date,
            y=Y1,
            name = name1,
#            yaxis='y',
            line = dict(color = '#17BECF',width=3),
            opacity = 0.8)

    trace_2 = go.Scatter(
            x=date,
            y=Y2,
            name = name2,
#            yaxis='y2',
            line = dict(color = '#7F7F7F',width=3),
            opacity = 0.8)

    data = [trace_1,trace_2]

    layout = dict(
            title=TITLE,
            #start of xaxis
            xaxis=dict(
                rangeselector=dict(
                    buttons=list([
                        dict(count=1,
                             label='1m',
                             step='month',
                             stepmode='backward'),
                        dict(count=3,
                             label='3m',
                             step='month',
                             stepmode='backward'),
                        dict(count=6,
                             label='6m',
                             step='month',
                             stepmode='backward'),
                        dict(count=1,
                             label='YTD',
                             step='year',
                             stepmode='todate'),
                        dict(count=1,
                             label='1y',
                             step='year',
                             stepmode='backward'),
                        dict(count=3,
                             label='3y',
                             step='year',
                             stepmode='backward'),
                        dict(count=5,
                             label='5y',
                             step='year',
                             stepmode='backward'),
                        dict(step='all')
                        ])
                ),
            rangeslider=dict(
                visible = True
            ),
                type='date'
            ),
        #end of xaxis
        legend=dict(orientation="h")
            
    )

    fig = dict(data=data, layout=layout)
    #fileopt='overwrite'
    url=py.plot(fig,auto_open=False,filename='SVI',fileopt='overwrite')
    return url
    name = 'Credit Risk = Good'
)

trace2 = go.Histogram(
    x = risk_eq_bad__by_ages,
    histnorm = 'probability',
    name = 'Credit Risk = Bad'
)

# make graph

fig = tls.make_subplots(rows=2,cols = 1,shared_xaxes=False)
fig.append_trace(trace1,1,1)
fig.append_trace(trace2,2,1)
fig['layout'].update(showlegend=True,title='Credit Risk by Age Distribution', bargap=0.05)
py.plot(fig , filename = 'AgeDist', auto_open=True)

# Let's search some correlation between credit amount and credit risk

risk_eq_good_by_ca = data.loc[data['Risk'] == 'good']['Credit amount'].values.tolist()
risk_eq_bad__by_ca = data.loc[data['Risk'] == 'bad']['Credit amount'].values.tolist()
index_for_ca_riskG = data.loc[data['Risk'] == 'good']['Credit amount'].index.values.tolist()
index_for_ca_riskB = data.loc[data['Risk'] == 'bad']['Credit amount'].index.values.tolist()

# create lines

trace1 = go.Scatter(
    x = index_for_ca_riskG,
    y = risk_eq_good_by_ca,
    name = 'Good Credit Risk'
)
Example #42
0
            txt_row.append("no data")
    z.append(list(new_row))
    ztxt.append(list(txt_row))

print(len(z[-1]))
print(len(z[0]))
print(len(z))
data = [
    go.Heatmap(z=z,
               text=ztxt,
               y=xchart,
               x=ychart,
               colorscale=[[0.0, 'rgb(49,54,149)'],
                           [0.1111111111111111, 'rgb(69,117,180)'],
                           [0.1515151515151515, 'rgb(116,173,209)'],
                           [0.2222222222222222, 'rgb(171,217,233)'],
                           [0.2626262626262626, 'rgb(224,243,248)'],
                           [0.3333333333333333, 'rgb(254,224,144)'],
                           [0.3939393939393939, 'rgb(253,174,97)'],
                           [0.5959595959595959, 'rgb(244,109,67)'],
                           [0.8888888888888888, 'rgb(215,48,39)'],
                           [1.0, 'rgb(165,0,38)']])
]

layout = go.Layout(title='Temperature Intake in kelvin ESP01',
                   xaxis=dict(ticks='', nticks=36),
                   yaxis=dict(ticks=''))

fig = go.Figure(data=data, layout=layout)
py.plot(fig, filename='temp-heatmap-intake-ESP01')
Example #43
0
    open_rate = "{}%".format(int(o.get('open_rate', 0)))
    x.append(o.get('email_subject'))
    y.append(open_rate)

data2 = [go.Bar(
    x=x,
    y=y,
    # orientation='h',
    text=y,
    textposition='inside',
    opacity=0.7,
    marker=dict(
        color=['rgb(49,130,189)', 'rgb(58,200,225)', 'rgb(58,200,225)', 'rgb(58,200,225)', 'rgb(58,200,225)'],
        line=dict(
            color='rgb(49,130,189)',
            width=1.5,
        )
    ))]

layout2 = go.Layout(
    title='Top 5 Posts by Open Rate',
)

fig2 = go.Figure(data=data2, layout=layout2)

# update charts
print("Refreshing Top Opens chart...\n")
py.plot(fig, filename='Top 5 Posts by Email Opens')
print("Refreshing Top Open Rate chart...\n")
py.plot(fig2, filename='Top 5 Posts by Open Rate')
Example #44
0
traceControl = Scatter(x=Control_enzymeConcentration,
                       y=Control_enzymeRate,
                       mode='markers+lines',
                       name='Alk.Phos. control',
                       marker=Marker(symbol='x', size=9),
                       line=Line(color=blue, width=0.5))

traceInhibitor = Scatter(x=Inhibitor_enzymeConcentration,
                         y=Inhibitor_enzymeRate,
                         mode='markers+lines',
                         name='Alk.Phos. + inhibitor',
                         marker=Marker(symbol='x', size=9),
                         line=Line(color=red, width=0.5))

figure = Figure(data=Data([traceControl, traceInhibitor]),
                layout=Layout(title=title2,
                              xaxis=XAxis(title='[PNPP] (ug/mL)',
                                          showgrid=True,
                                          zeroline=True,
                                          gridwidth=0.8),
                              yaxis=YAxis(title='vi (au(410nm)/min)',
                                          showgrid=True,
                                          zeroline=True,
                                          gridwidth=0.8),
                              font=dict(size=12),
                              titlefont=dict(size=20)))
py.plot(figure,
        filename='Enzyme Kinetics Plot 2a',
        stream=Stream(token=stream_ids[1], maxpoints=1000))
Example #45
0
                                title='RSSI @ %sft.' % distance,
                                titlefont=dict(family='verdana',
                                               size=18,
                                               color='#7F7F7F')),
                     legend=dict(
                         x=0.7070486656200942,
                         y=1.1242331288343559,
                     ))

insideTrace = Scatter(x=ticksInside,
                      y=rssiInsideVals,
                      mode='lines+markers',
                      name='Inside Hat',
                      marker=Marker(size=3,
                                    color='#ff7f0e',
                                    symbol='circle-open',
                                    line=dict(width=1.5)))

outsideTrace = Scatter(x=ticksOutside,
                       y=rssiOutsideVals,
                       mode='lines+markers',
                       name='Outside Hat',
                       marker=Marker(size=3,
                                     color='#1F77B4',
                                     symbol='circle-open',
                                     line=dict(width=1.5)))

graphData = [insideTrace, outsideTrace]
graphFig = dict(data=graphData, layout=graphLayout)
py.plot(graphFig, filename='RSSI @ %sft.' % distance)
def PlotTopicDistribution(p_topic_dist, p_num_plot_topics, p_topic_palette,
                          p_plot_type, p_chart_title):

    # Note: p_topic_dist is assumed to be ordered by topic ID only

    # 1. Create ordered tuple lists for topic IDs and topic weights depending on desired plot type
    topic_ids = []
    topic_weights = []
    color_list = []  #"elements are hex(#hexcolor)"
    if p_plot_type == "descending":

        sorted_topic_dist = []
        for index in range(len(p_topic_dist)):
            sorted_topic_dist.append((index, p_topic_dist[index]))
        sorted_topic_dist = sorted(sorted_topic_dist,
                                   key=lambda x: x[1],
                                   reverse=True)
        for index in range(len(sorted_topic_dist)):
            topic_ids.append("Topic " + str(sorted_topic_dist[index][0]))
            topic_weights.append(sorted_topic_dist[index][1])

        # Plot is limited by the suggested amount of topics
        full_topic_count = len(p_topic_dist)
        if p_num_plot_topics > full_topic_count:
            p_num_plot_topics = full_topic_count
        if p_num_plot_topics != full_topic_count:
            topic_ids = topic_ids[0:p_num_plot_topics]
            topic_weights = topic_weights[0:p_num_plot_topics]

    else:  # bullseye plot

        sorted_topic_dist = []
        for index in range(len(p_topic_dist)):
            sorted_topic_dist.append((index, p_topic_dist[index]))
        sorted_topic_dist = sorted(sorted_topic_dist,
                                   key=lambda x: x[1],
                                   reverse=True)

        # Bullseye distribution
        topic_ids.append("Topic " + str(sorted_topic_dist[0][0]))
        topic_weights.append(sorted_topic_dist[0][1])
        full_topic_count = len(p_topic_dist)
        plot_limit = full_topic_count
        if p_num_plot_topics < full_topic_count:
            plot_limit = p_num_plot_topics
        for index in range(1, plot_limit):
            topic_ids.insert(
                0, "Topic " + str(sorted_topic_dist[index][0]) + "_L")
            topic_weights.insert(0, sorted_topic_dist[index][1])
            topic_ids.append("Topic " + str(sorted_topic_dist[index][0]) +
                             "_R")
            topic_weights.append(sorted_topic_dist[index][1])

    # 2. Create a marker list based on the topic IDs in the distribution
    for index in range(len(topic_ids)):

        topic_id_num = topic_ids[index][6:]

        if "bullseye" == p_plot_type and "_" in topic_id_num:
            topic_id_num = topic_id_num[0:topic_id_num.find("_")]

        color_list.append(p_topic_palette[int(topic_id_num)])

    # 3. Create Plotly data structures
    trace0 = go.Bar(
        x=topic_ids,
        y=topic_weights,
        marker=dict(color=color_list, ),
    )
    data = [trace0]
    layout = go.Layout(title=p_chart_title, )
    fig = go.Figure(data=data, layout=layout)

    # 4. Plot the distribution
    plot_url = py.plot(fig,
                       filename=p_chart_title.replace(" ", "-") + "-" +
                       p_plot_type)
Example #47
0
    trace1 = go.Scatter(x=ty, y=ay - np.mean(ay), mode='markers', name='ay')
    trace2 = go.Scatter(x=tz, y=az - np.mean(az), mode='markers', name='az')
    data = go.Data([trace0, trace1, trace2])

    layout = go.Layout(
        dict(title='Acceleration vs. Time',
             xaxis=dict(title='Time (HH:MM:SS)'),
             yaxis=dict(title='Acceleration  (m/s^2)')))
    '''
    fig = plotly.tools.make_subplots(rows=2, cols=1)
    fig.append_trace(trace0, 1, 1)
    fig.append_trace(trace1, 1, 1)
    fig.append_trace(trace2, 1, 1)
    fig['layout'].update(title='Acceleration vs Time')
    '''
    fig = go.Figure(data=data, layout=layout)
    '''
    trace3 = go.Scatter(x=freqx,y=powerx,
                    mode='markers',
                    name='FFTx',
                    )
    trace4 = go.Scatter(x=freqy,y=powery,mode='markers',name='FFTy')
    trace5 = go.Scatter(x=freqz,y=powerz,mode='markers',name='FFTz')
    data2 = go.Data([trace3,trace4, trace5])
    fig.append_trace(trace3, 2, 1)
    fig.append_trace(trace4, 2, 1)
    fig.append_trace(trace5, 2, 1)    
    
    '''
    py.plot(fig, filename='acceleration-data')
# Written by Jonathan Saewitz, released May 24th, 2016 for Statisti.ca
# Released under the MIT License (https://opensource.org/licenses/MIT)

import csv, plotly.plotly as plotly
from collections import Counter

c = Counter()

with open('presidential_candidates.csv', 'r') as f:
    reader = csv.reader(f)
    reader.next()  #skip the headers row
    for row in reader:  #loop through the candidates
        if row[1] == 'C':  #row[1] is the candidate's status; 'C' means statutory candidate
            party = row[12]  #row[12] is the candidate's political party
            c[party] += 1

fig = {
    'data': [{
        'labels': c.keys(),
        'values': c.values(),
        'type': 'pie'
    }],
    'layout': {
        'title':
        '2016 US Statutory Presidential Candidates\' Party Affiliation'
    }
}

plotly.plot(fig)
        l=40,
        b=40,
        r=120,
        pad=0,
    ),
    # LEGEND
    legend=dict(
        x=1.02,
        y=1,
        font=dict(size=10),
    ),

    hovermode='closest',
    mapbox=go.layout.Mapbox(
        accesstoken=mapBoxToken,
        style="dark",
        bearing=0,
        center=go.layout.mapbox.Center(
            lat=48.35,
            lon=-99.99,

        ),
        pitch=0,


    ),
)

figure = dict(data=traces, layout=layout)
py.plot(figure, filename='Oil Assset Map')
Example #50
0
    name='High 2007',
    line=dict(color=('rgb(205, 12, 24)'), width=4,
              dash='dash')  # dash options include 'dash', 'dot', and 'dashdot'
)
trace3 = go.Scatter(x=month,
                    y=low_2007,
                    name='Low 2007',
                    line=dict(color=('rgb(22, 96, 167)'), width=4,
                              dash='dash'))
trace4 = go.Scatter(x=month,
                    y=high_2000,
                    name='High 2000',
                    line=dict(color=('rgb(205, 12, 24)'), width=4, dash='dot'))
trace5 = go.Scatter(x=month,
                    y=low_2000,
                    name='Low 2000',
                    line=dict(color=('rgb(22, 96, 167)'), width=4, dash='dot'))
data = [trace0, trace1, trace2, trace3, trace4, trace5]

# Edit the layout
layout = dict(
    title='Average High and Low Temperatures in New York',
    xaxis=dict(title='Month'),
    yaxis=dict(title='Temperature (degrees F)'),
)

fig = dict(data=data, layout=layout)
py.plot(fig, filename='styled-line')

plotly.offline.plot(fig, filename='styled-line')
Example #51
0
def plot_speciesloc():
    lat_all = []
    lon_all = []
    name_all = []

    for each in spe_nm_loc:
        lat_all.append(each[0])
        lon_all.append(each[1])
        name_all.append(spe_nm_loc[each])

    data = Data([
        Scattermapbox(lat=lat_all,
                      lon=lon_all,
                      text=name_all,
                      mode='markers',
                      marker=dict(size=20,
                                  symbol="circle",
                                  color="rgb(27, 167, 132)"))
    ])
    #### find max range
    min_lat = 10000
    max_lat = -10000
    min_lon = 10000
    max_lon = -10000

    for each in lat_all:
        each_f = float(each)
        if each_f < min_lat:
            min_lat = each_f
        if each_f > max_lat:
            max_lat = each_f
    for each in lon_all:
        each_f = float(each)
        if each_f < min_lon:
            min_lon = each_f
        if each_f > max_lon:
            max_lon = each_f

    center_lat = (max_lat + min_lat) / 2
    center_lon = (max_lon + min_lon) / 2
    max_range = max(abs(max_lat - min_lat), abs(max_lon - min_lon))
    padding = max_range * .10
    lat_axis = [min_lat - padding, max_lat + padding]
    lon_axis = [min_lon - padding, max_lon + padding]

    layout = dict(geo=dict(scope='world',
                           showland=True,
                           landcolor="rgb(229, 229, 229)",
                           countrycolor="rgb(255, 255, 255)",
                           coastlinecolor="rgb(255, 255, 255)",
                           lataxis={'range': lat_axis},
                           lonaxis={'range': lon_axis},
                           center={
                               'lat': center_lat,
                               'lon': center_lon
                           },
                           countrywidth=3,
                           subunitwidth=3), )

    fig = dict(data=data, layout=layout)
    py.plot(fig, filename='Multiple Mapbox')
    return None
Example #52
0
        [
            -2.23398006, -1.55343536, -1.00424328, 0.75614508, 2.74500261,
            -1.66698498, 3.53602341, 2.31842582, 3.82492448, 2.10852554
        ],
        [
            0.10376833, -4.01058726, -5.17869981, -6.91027253, -1.32858634,
            -7.17423945, -4.24552815, -0.86084939, -1.23227484, -6.93129655
        ],
        [
            -3.7931981, -8.32937243, -2.4994021, -7.11710495, -0.70963085,
            -4.59666308, -4.35177052, -5.25894582, -5.35001709, -6.28746534
        ]]

twosample_results = scipy.stats.ttest_ind(mean[2], mean[5])

matrix_twosample = [['', 'Test Statistic', 'p-value'],
                    [
                        'Sample Data', twosample_results[0],
                        twosample_results[1]
                    ]]

twosample_table = ff.create_table(matrix_twosample, index=True)
print(twosample_table)
py.plot(twosample_table, filename='twosample-table')

for i in range(3):
    plt.subplot(2, 2, i + 1)
    plt.boxplot(mean[i], mean[i + 3], 'gD')

plt.show()
Example #53
0
    def handle(self, *args, **options):
        GET = {'gender_id': 1, 'year': 2012}
        gender_id = GET.get('gender_id', '')
        education_level_id = GET.get('education_level_id', '')
        income_level_id = GET.get('income_level_id', '')
        year = GET.get('year', '')

        items = IncomeData.objects.all()
        if gender_id != '':
            items = items.filter(gender_id=gender_id)
        if year != '':
            items = items.filter(year=year)
        if income_level_id != '':
            items = items.filter(income_level_id=income_level_id)
        if education_level_id != '':
            items = items.filter(education_level_id=education_level_id)


        # gender_id is '', so all genders
        # 23904823094, baker county, IL, male, 56
        # 23904823094, baker county, IL, female, 102

        # sum up all rows for a given county
        # start with an empty 'output' list
        # loop over all the items
        # if there already exists an item in the output list with the given county id
        # then add the population to it
        # otherwise add it

        counter = 0
        output = {}
        for item in items:
            if item.county.fips == '':
                continue

            if item.county.fips in output:
                output[item.county.fips] += item.population
            else:
                output[item.county.fips] = item.population

            if counter%10 == 0:
                print(f'{round(counter/len(items)*100,2)}%')
            counter += 1

        fips = list(output.keys())
        values = list(output.values())

        top_populations = list(sorted(values, reverse=True))[:20]
        max_value = sum(top_populations)/len(top_populations)/10

        colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1",
                      "#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9",
                      "#08519c", "#0b4083", "#08306b"]
        endpts = list(np.linspace(0, max_value, len(colorscale) - 1))

        print(endpts)
        # fips = df_sample['FIPS'].tolist()
        # values = df_sample['Unemployment Rate (%)'].tolist()
        #
        fig = ff.create_choropleth(
            fips=fips, values=values, scope=['usa'],
            binning_endpoints=endpts, colorscale=colorscale,
            show_state_data=False,
            show_hover=True, centroid_marker={'opacity': 0},
            asp=2.9, title='USA by Unemployment %',
            legend_title='% unemployed'
        )
        url = py.plot(fig, filename='choropleth_full_usa')
    mode='lines',
    name='Global_Avg_Temp'
)
trace2 = go.Scatter(
    x=Seattle['year'],
    y=Seattle['city_avg_temp'],
    mode='lines',
    name='Seattle_Avg_Temp'
)
trace3 = go.Scatter(
    x=NewYork['year'],
    y=NewYork['city_avg_temp'],
    mode='lines',
    name='NewYork_Avg_Temp'
)

layout = go.Layout(
    title='Exploring Weather Trends',
        xaxis=dict(
            title='Year'
        ),
        yaxis=dict(
            title='Temperature in ( C )'
        )
    )

fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)

# Plot data in the notebook
py.plot(fig, filename='Exploring Weather Trends')
Example #55
0
def plot_all_ew_tl_alg_vehicles(static, actuated, dynamic):
    size = list(range(len(static)))

    layout = graph_objs.Layout(

        title='East/West Vehicles Waiting Over All Three Algorithms',
        xaxis=dict(
            title='Time (s)',
            titlefont=dict(
                family='Courier New, monospace',
                size=18,
                color='#7f7f7f'
            )

        ),
        yaxis=dict(
            title='Num Vehicles',
            titlefont=dict(
                family='Courier New, monospace',
                size=18,
                color='#7f7f7f'
            ),
            range=range_val

        ),
        legend=dict(
            traceorder='normal',
            font=dict(
                family='sans-serif',
                size=16,
                color='#000'
            ),
            bgcolor='#E2E2E2',
            bordercolor='#FFFFFF',
            borderwidth=2
        )
    )

    static = Scatter(
        x=size,
        y=static,
        marker=dict(color="green"),
        name="Static"
    )
    actuated = Scatter(
        x=size,
        y=actuated,
        marker=dict(color="blue"),
        name="Actuated"
    )
    dynamic = Scatter(
        x=size,
        y=dynamic,
        marker=dict(color="red"),
        name="Dynamic"
    )

    data = [static, actuated, dynamic]
    fig = graph_objs.Figure(data=data, layout=layout)

    py.plot(fig, filename='east-west-all-num-vehicles-waiting')
def submit():
    # grab data from form
    function_a = request.forms.get('function_a')
    function_b = request.forms.get('function_b')
    MIN = request.forms.get('MIN')
    MAX = request.forms.get('MAX')

    # set up domain
    MIN = float(MIN)
    MAX = float(MAX)
    NUM = 100
    xvals = np.linspace(MIN, MAX, NUM)

    # set up original curves by populating lists with eval() outputs
    a_yvals = []
    b_yvals = []
    for x in xvals:
        a_yvals.append(eval(function_a))
        b_yvals.append(eval(function_b))

    # get what we have so far into the data
    zvals = xvals * 0
    line_a = go.Scatter3d(x=xvals,
                          y=a_yvals,
                          z=zvals,
                          mode='lines',
                          line=dict(color='red', width=4))

    line_b = go.Scatter3d(x=xvals,
                          y=b_yvals,
                          z=zvals,
                          mode='lines',
                          line=dict(color='blue', width=4))
    data = [line_a, line_b]

    # take each point on curve B, approximate tangent line to it, make perpendicular line to the tangent,
    # find point on curve A that it intersects, draw a circle with this point around B:
    for i in range(len(xvals)):

        b_x = xvals[i]
        b_y = b_yvals[i]

        # dont make a circle of radius 0...
        if a_yvals[i] == b_y:
            continue

        # get perpendicular slope to reflection point on curve B
        # use approx of slope
        if i >= 1:
            tan_slope = (b_yvals[i] - b_yvals[i - 1]) / (xvals[i] -
                                                         xvals[i - 1])
        else:
            tan_slope = (b_yvals[i] - b_yvals[i + 1]) / (xvals[i] -
                                                         xvals[i + 1])

        # find approx where perp_line and rotating line intersect
        solutions = []
        if tan_slope == 0:  # must make it so that flat lines work too
            solutions.append(b_x)
        else:
            # perpendicular is neg recip
            slope = tan_slope**(-1)
            slope = -slope
            perp_line = slope * (xvals - b_x) + b_y

            # check when difference in yvals changes sign, approx intersection
            positive = None
            for j in range(len(xvals)):
                diff = perp_line[j] - a_yvals[j]
                old_positive = positive
                if diff > 0:
                    positive = True
                elif diff == 0:
                    solutions.append(xvals[j])
                else:
                    positive = False

                if old_positive != None:
                    if old_positive != positive:
                        solutions.append(xvals[j])

        # make a circle for every solution
        for a_x in solutions:

            # for eval() to work it must be an 'x'
            x = a_x
            a_y = eval(function_a)

            # calc radius, plot line of circle diameter otherwise
            if tan_slope == 0:  # again, making sure it works for vertical lines
                radius = np.abs(a_y - b_y)
                circle_xs = [a_x] * 50
                circle_ys = np.linspace(b_y - radius, b_y + radius, 50)
            else:
                # radius of circle is dist btwn point on line A and point on line B
                delta_x = np.abs(float(b_x - a_x))
                delta_y = np.abs(float(b_y - a_y))
                radius = np.sqrt((delta_x)**2 + (delta_y)**2)

                # make a line segment on xy plane that is circle's diameter
                circle_xs = np.linspace(b_x - delta_x, b_x + delta_x, 50)
                circle_ys = slope * (circle_xs - b_x) + b_y

            # z points are a function of x and y, make a circle
            circle_zs = []
            for k in range(len(circle_xs)):
                # solve for z in distance formula
                magnitude = np.sqrt(radius**2 - (circle_xs[k] - b_x)**2 -
                                    (circle_ys[k] - b_y)**2)

                # bottom and top of circle
                circle_zs.append(magnitude)
                circle_zs.append(-magnitude)

            # double all the points on the x and y axes to account for top and bottom of circle
            circle_xs = np.repeat(circle_xs, 2)
            circle_ys = np.repeat(circle_ys, 2)

            # add this circle too the data list and do the next one
            circle = go.Scatter3d(x=circle_xs,
                                  y=circle_ys,
                                  z=circle_zs,
                                  mode='lines',
                                  opacity=.1,
                                  line=go.Line(color='green', width=2))

            data.append(circle)

    ### make sure it's not distorted
    diff = MAX - MIN + 4  # length of one side of cubic graph
    diff = diff / 2.0  # half so we can start from midpoint
    # determine where the middle of the graph is on the y axis
    a_yvalsMIN = min(a_yvals)
    a_yvalsMAX = max(a_yvals)
    b_yvalsMIN = min(b_yvals)
    b_yvalsMAX = max(b_yvals)
    YMAX = max(a_yvalsMIN, b_yvalsMIN)
    YMIN = min(a_yvalsMAX, b_yvalsMAX)
    ymiddle = YMIN + (YMAX - YMIN) / 2.0

    # set the axis limits to be a nice cube
    layout = go.Layout(
        title="Rotated Functions",
        scene=go.Scene(
            xaxis=dict(
                autorange=False,
                showspikes=False,
                range=[MIN - 2, MAX + 2]  # set axis range
            ),
            yaxis=dict(autorange=False,
                       showspikes=False,
                       range=[ymiddle - diff, ymiddle + diff]),
            zaxis=dict(autorange=False, showspikes=False, range=[-diff,
                                                                 diff])),
        showlegend=False,
        hovermode=False)

    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename=file, auto_open=False)

    return template('html2', plot_url=str(plot_url) + ".embed")
Example #57
0
tls.set_credentials_file(username="******", api_key="c6hv1155p9")

tokens = ["8nkkf6evch"]

trace1 = Scatter(
        x=[],
        y=[],
        stream=dict(token="8nkkf6evch")
    )

trace2 = Scatter(
        x=[],
        y=[],
        stream=dict(token="j7zoksx3c0")
    )

data = Data([trace1,trace2])
py.plot(data)
s = py.Stream("8nkkf6evch")
s.open()
s.write(dict(x=1, y=2))



s1 = py.Stream("j7zoksx3c0")
s1.open()
s1.write(dict(x=2, y=1))
s1.close()

s.close()
Example #58
0
import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Bar(
    x=['Product A', 'Product B', 'Product C'],
    y=[20, 14, 23],
    text=['27% market share', '24% market share', '19% market share'],
    marker=dict(
        color='rgb(158,202,225)',
        line=dict(
            color='rgb(8,48,107)',
            width=1.5,
        )
    ),
    opacity=0.6
)
data = [trace0]
layout = go.Layout(
    title='January 2013 Sales Report',
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='text-hover-bar')
import plotly.plotly as py
from plotly.graph_objs import *
from getpass import getpass
import numpy as np
import pandas as pd

df = pd.read_csv('transcount.csv')
df = df.groupby('year').aggregate(np.mean)

gpu = pd.read_csv('gpu_transcount.csv')
gpu = gpu.groupby('year').aggregate(np.mean)

df = pd.merge(df, gpu, how='outer', left_index=True, right_index=True)
df = df.replace(np.nan, 0)

api_key = getpass()

# Change the user to your own username
py.sign_in('LearningPythonDataAnalysis', api_key)

counts = np.log(df['trans_count'].values)
gpu_counts = np.log(df['gpu_trans_count'].values)

data = Data([Box(y=counts), Box(y=gpu_counts)])
plot_url = py.plot(data, filename='moore-law-scatter')
print plot_url
Example #60
0
                   height=1000,
                   yaxis=go.layout.YAxis(
                       title="Ratings",
                       ticktext=values,
                       automargin=True,
                       titlefont=dict(size=30),
                   ),
                   xaxis=go.layout.XAxis(
                       ticktext=labels,
                       automargin=True,
                       titlefont=dict(size=30),
                   ))

fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='automargin')
plot_url = py.plot(fig)
'''Start new visualization


'''
title = "Top Ten Song Ratings Over Time"
cur.execute("SELECT song_title, rating FROM TopSpotifyData")
top_wed_dictionary = {}
for row in cur:
    song = row[0]
    rating = row[1]
    if song not in top_wed_dictionary:
        top_wed_dictionary[song] = rating
    else:
        top_wed_dictionary[song] += rating