def get_time_insights(df):

    pop_cust_hour, pop_subs_hour, pop_hour = {}, {}, {}
    for day in bs.DAYS:
        dayframe = df[df['day_of_week'] == day]
        # pop_hour[day] = dayframe['hour'].mode()[0]

        cust_frame = dayframe[dayframe['User Type'] == 'Customer']
        pop_cust_hour[day] = cust_frame['hour'].mode()[0]

        subs_frame = dayframe[dayframe['User Type'] == 'Subscriber']
        pop_subs_hour[day] = subs_frame['hour'].mode()[0]

    traces = [
        go.Line(x=list(pop_cust_hour.keys()),
                y=list(pop_cust_hour.values()),
                name='Customer',
                marker=go.scatter.Marker(color='rgb(55, 83, 109)')),
        go.Line(x=list(pop_subs_hour.keys()),
                y=list(pop_subs_hour.values()),
                name='Subscriber',
                marker=go.scatter.Marker(color='rgb(26, 118, 255)'))
    ]

    return traces
예제 #2
0
파일: circle2.py 프로젝트: volunL/plotly
def GetTrace(datalist):
    tracelist = []
    for data in datalist:
        trace = go.Bar(
            x=data["x"],
            y=data["y"],
            width=0.03
            #mode="lines",
            #  line=dict(
            #      color="#feb4d1"
            #  ),
        )

        tracelist.append(trace)

    sinData = SinData()
    trace = go.Scatter(x=sinData['x'],
                       y=sinData['y'],
                       line=go.Line(color='#eeeeee'))
    tracelist.append(trace)

    osinData = oSinData()
    trace = go.Scatter(x=osinData['x'],
                       y=osinData['y'],
                       line=go.Line(color='#eeeeee'))
    tracelist.append(trace)

    return tracelist
예제 #3
0
def update_graph(input_value, c1, c2, yr, mon):
    data = []
    df_industry = df_eda[df_eda['Industry'] == input_value]
    df_industry = df_industry[df_industry['Year'] == yr]
    df_industry = df_industry[df_industry['Month_y.1'] == mon]
    trace = go.Line(x=df_industry['Date_New_quarterly'].values,
                    y=df_industry['marketcap'].values,
                    text=df_industry['Industry'],
                    mode='line',
                    name="Market Cap",
                    line_color='rgb(231,107,243)',
                    marker=dict(color=c1))
    data1 = go.Line(x=df_industry['Date_New_quarterly'],
                    y=df_industry.groupby(['Industry', 'Date_New_quarterly'
                                           ])['marketcap'].sum(),
                    mode="line",
                    text=df_industry['Industry'],
                    name="Total Market Cap",
                    line_color='rgb(0,176,246)',
                    marker=dict(color=c2))
    data.append(trace)
    data.append(data1)
    layout = dict(xaxis={'title': "Date"},
                  yaxis={'title': "Market cap & Total Market cap"},
                  margin={
                      'l': 40,
                      'b': 40,
                      't': 10,
                      'r': 0
                  },
                  hovermode='closest')
    return {"data": data, "layout": layout}
예제 #4
0
def populate_trace_for_extend(x=None,
                              y=None,
                              graph_legend_item_name='',
                              trace_unique_id='',
                              trace_unique_id_pattern=None,
                              shape_type=''):
    #series list must be completely filled in using graph create order
    #'text' param if added generates error
    if not trace_unique_id_pattern:
        trace_unique_id_pattern = []
    if not x:
        x = []
    trace_pos = trace_unique_id_pattern.index(trace_unique_id)
    trace_list = []
    for i in range(len(trace_unique_id_pattern)):
        if i == trace_pos:
            trace_extend = graph_objs.Scatter(
                x=x,
                y=y,
                name=graph_legend_item_name,
                line=graph_objs.Line(shape=shape_type))
            trace_list.append(trace_extend)
        else:
            trace_empty = graph_objs.Scatter(
                x=[], y=[], line=graph_objs.Line(shape=shape_type))
            trace_list.append(trace_empty)
    L.l.debug('Extending graph serie {} {}'.format(graph_legend_item_name,
                                                   trace_unique_id))
    return trace_list
예제 #5
0
def update_graph(type):
    if type == 'All':
        mask = data.groupby('Date')['Deaths'].max().sort_values(
            ascending=True).reset_index()
        return {
            'data': [go.Line(x=mask['Date'], y=mask['Deaths'])],
            'layout':
            go.Layout(title='Number of Deaths Per Day',
                      xaxis={'title': 'Dates'},
                      yaxis={'title': 'Number of Deaths'},
                      paper_bgcolor='rgba(0,0,0,1)',
                      plot_bgcolor='rgba(0,0,0,1)')
        }
    else:
        mask = data[data['Country/Region'] == type]
        masks = mask.groupby('Date')['Deaths'].max().sort_values(
            ascending=True).reset_index()
        return {
            'data': [go.Line(x=masks['Date'], y=masks['Deaths'])],
            'layout':
            go.Layout(title='Number of Deaths Per Day',
                      xaxis={'title': 'Dates'},
                      yaxis={'title': 'Number of Deaths'},
                      paper_bgcolor='rgba(0,0,0,1)',
                      plot_bgcolor='rgba(0,0,0,1)')
        }
예제 #6
0
def draw_graph(G, stations):
    node_trace = go.Scatter(
        x=[],
        y=[],
        text=[],
        mode='markers+text',
        textposition='top center',
        textfont=dict(
            family='arial',
            size=3,
            color='rgb(0,0,0)'
        ),
        hoverinfo='none',
        marker=go.Marker(
            showscale=False,
            color='rgb(200,0,0)',
            opacity=0.3,
            size=8,
            line=go.Line(width=1, color='rgb(0,0,0)')))

    node_positions = {}
    for id in stations.index:
        lat, lng = stations.loc[id, ["Latitude", "Longitude"]].values
        node_positions[id] = [lat, lng]
        node_trace['x'].append(lat)
        node_trace['y'].append(lng)
        # node_trace['text'].append(id)

    # The edges will be drawn as lines:
    edge_trace = go.Scatter(
        x=[],
        y=[],
        line=go.Line(width=2, color='rgb(10,10,10)'),
        hoverinfo='none',
        mode='lines')

    for id in node_positions.keys():
        for neigh_info in G.neighbors(id):
            x0, y0 = node_positions[id]
            x1, y1 = node_positions[neigh_info[0]]
            edge_trace['x'].extend([x0, x1, None])
            edge_trace['y'].extend([y0, y1, None])

    # Create figure:
    fig = go.Figure(data=go.Data([edge_trace, node_trace]),
                    layout=go.Layout(
                        title='Sample Network',
                        titlefont=dict(size=16),
                        showlegend=False,
                        hovermode='closest',
                        margin=dict(b=20, l=5, r=5, t=40),
                        xaxis=go.XAxis(showgrid=False, zeroline=False, showticklabels=False),
                        yaxis=go.YAxis(showgrid=False, zeroline=False, showticklabels=False)))

    py.plot(fig)
예제 #7
0
def createFigure(filename, isAutoOpen=True, isUploadToServer=False):
    # ------------Custom Candlestick Colors------------
    # Make increasing ohlc sticks and customize their color and name
    opens = [datarow.open for datarow in dataRows]
    highs = [datarow.high for datarow in dataRows]
    lows = [datarow.low for datarow in dataRows]
    closes = [datarow.close for datarow in dataRows]

    fig_increasing = FigureFactory.create_candlestick(
        opens,
        highs,
        lows,
        closes,
        dates=datetime_xAxis,
        direction='increasing',
        marker=go.Marker(color='rgb(61, 153, 112)'),
        line=go.Line(color='rgb(61, 153, 112)'))

    # Make decreasing ohlc sticks and customize their color and name
    fig_decreasing = FigureFactory.create_candlestick(
        opens,
        highs,
        lows,
        closes,
        dates=datetime_xAxis,
        direction='decreasing',
        marker=go.Marker(color='rgb(255, 65, 54)'),
        line=go.Line(color='rgb(255, 65, 54)'))

    # Initialize the figure
    fig = fig_increasing
    fig['data'].extend(fig_decreasing['data'])

    # ------------Add extensions------------
    for index, extensionList in enumerate(extensionLists):
        addLineExtension(fig, [data[0] for data in extensionList],
                         [data[1]
                          for data in extensionList], extensionNames[index],
                         extensionLineTypes[index], extensionColors[index])

    # ------------Update layout And Draw the chart------------
    filename = chartTitle
    fig['layout'].update(
        title=filename,
        xaxis=dict(ticktext=[datarow.date for datarow in dataRows],
                   tickvals=datetime_xAxis,
                   showticklabels=False,
                   showgrid=True,
                   showline=True),
    )

    plotly.offline.plot(fig, filename=filename + '.html', auto_open=isAutoOpen)
    print "----------The chart has been generated----------\n"
예제 #8
0
def build_data(digraph):
    if digraph.nodes():
        first_node = list(digraph.nodes)[0]
        node_pos = nx.spring_layout(digraph, pos={first_node:(0,0)}, fixed=[first_node], seed=1)
        maxX.append(max([pos[0] for pos in node_pos.values()]))
        maxY.append(max([pos[1] for pos in node_pos.values()]))
        minX.append(min([pos[1] for pos in node_pos.values()]))
        minY.append(min([pos[1] for pos in node_pos.values()]))
    else:
        node_pos = nx.spring_layout(digraph, seed=1)



    node_trace = go.Scatter(
        x=[pos[0] for pos in node_pos.values()],
        y=[pos[1] for pos in node_pos.values()],
        text=name_list,
        mode='markers+text',
        textposition='top center',
        textfont=dict(
            family='arial',
            size=18,
            color='rgb(0,0,0)'
        ),
        hoverinfo='none',
        marker=go.Marker(
                showscale=False,
                color=[color_list[depth-1 % len(color_list)] for depth in depth_list],
                opacity=1,
                #size= [(start_size * 1/(depth)) for depth in depth_list],
                size= size_list,
                line=go.Line(width=1, color='rgb(0,0,0)')))

    edgesX = []
    edgesY = []
    for edge in digraph.edges:
        try:
            x0, y0 = node_pos[edge[0]]
            x1, y1 = node_pos[edge[1]]
            edgesX.extend([x0, x1, None])
            edgesY.extend([y0, y1, None])
        except KeyError:
            continue

    edge_trace = go.Scatter(
        x=edgesX,
        y=edgesY,
        line=go.Line(width=1, color='rgb(150,150,150)'),
        hoverinfo='none',
        mode='lines')

    return go.Data([edge_trace, node_trace])
예제 #9
0
def gen_main_graph(child):
    '''First trace'''
    trace = go.Scatter(y=data.data.tail(n=10).Price,
                       x=data.data.tail(n=10).index,
                       line=go.Line(color='#009688'),
                       hoverinfo='XBT/EUR',
                       mode='lines+markers')
    '''styking of the graph element'''
    layout = go.Layout(
        height=450,
        xaxis=dict(range=[
            data.data.tail(n=10).index.min(),
            data.data.tail(n=10).index.max()
        ],
                   showgrid=True,
                   showline=False,
                   zeroline=False,
                   fixedrange=False,
                   showticklabels=False),
        yaxis=dict(
            range=[
                min(list(data.data.tail(n=10).Price)) -
                Config.ranj * min(list(data.data.tail(n=10).Price)),
                max(list(data.data.tail(n=10).Price)) +
                Config.ranj * max(list(data.data.tail(n=10).Price))
            ],
            showline=False,
            fixedrange=True,
            zeroline=False,
        ),
        margin=go.Margin(
            t=45,
            l=100,
            r=100,
            b=50,
        ))

    basedata = [trace]
    '''Checks for the Checkboxes to add a trace to the graph'''
    if Config.input1 % 2 != 0:
        move = data.moving_average('Price')

        movave = go.Scatter(y=move.tail(n=10).Price,
                            x=move.tail(n=10).index,
                            line=go.Line(color='#00695c'),
                            hoverinfo='skip',
                            mode='lines+markers')

        basedata.append(movave)

    return go.Figure(data=basedata, layout=layout)
예제 #10
0
def update_graph(Manager):
    if Manager == "All Managers":
        df_plot = df.copy()
    else:
        df_plot = df.loc[Manager][
            'Probability of Exceeding Threshold (%) ']  #[df['Manager'] == Manager]

    # pv = pd.pivot_table(
    #     df_plot,
    #     index=['Name'],
    #     columns=["Status"],
    #     values=['Quantity'],
    #     aggfunc=sum,
    #     fill_value=0)

    trace1 = go.Line(x=df_plot.index,
                     y=df_plot.values.ravel(),
                     name='Probability of Exceeding Threshold (%) ')
    # trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
    # trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
    # trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')

    return {
        'data': [trace1],
        'layout':
        go.Layout(
            title='Probability of Rainfall Exceeding {} mm'.format(Manager),
            barmode='stack')
    }
예제 #11
0
def score_plot(matches, v):
    import chart_studio.plotly as py
    import plotly.graph_objs as go
    import plotly.offline as offline
    import plotly.express as px
    match = [lis for lis in matches if lis[1] != 0.0]
    total_recommendation = len(match)
    print(total_recommendation)
    #select top 60%
    score = [lis[1] for lis in matches if lis[1]]
    thres = round(max(score) * v, 2)
    score_thres = [lis[1] for lis in matches if lis[1] > thres]
    TP = len(score_thres)
    TN = 615 - total_recommendation
    FP = total_recommendation - TP
    print(TP, TN, FP)
    title = [lis[0] for lis in matches if lis[1] > thres]
    # plt.plot(title,score, color='g')
    # plt.xlabel('Title')
    # plt.ylabel('Score')
    # plt.title('Accuracy')
    # plt.show()
    data = [go.Line(x=title, y=score)]
    layout = go.Layout(title='Accuracy',
                       width=700,
                       height=700,
                       xaxis_type='category')
    fig = go.Figure(data=data, layout=layout)
    #offline.plot(fig,filename='Accuracy.html')
    precision = (TP / (TP + FP))
    recall = (TP / TP)
    F1 = 2 * ((precision * recall) / (precision + recall))
    return print(precision, recall, F1)
예제 #12
0
def create_plot(data):

	df = pd.DataFrame(data)
	cities=df['city'].unique()
	graphs=[]
	
	for city in cities:
		cityData=df.loc[df['city']==city]
		fig=go.Figure(go.Line(
				x=cityData['date'], # assign x as the dataframe column 'x'
				y=cityData['num_trips']
				))
		fig.update_layout(
		title=city,
		xaxis_title="Journey Date",
		yaxis_title="No. of Trips",
		font=dict(
			family="Courier New, monospace",
			size=18,
			color="#7f7f7f"
		))
		fig.layout.paper_bgcolor='rgba(0,0,0,0)'
		fig.layout.plot_bgcolor='rgba(0,0,0,0)'
		graphs.append(fig)
	ids = [cities[i] for i, _ in enumerate(graphs)]
	graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
	return [graphJSON,ids]
예제 #13
0
def line_trace_course_fr_diff(course_name,
                              colour,
                              semester=None,
                              dash_type=None,
                              showlegend=True):
    qry = qry_location_diff_history(course_name)
    df1 = db_extract_query_to_dataframe(qry,
                                        postgres_cur,
                                        print_messages=False)
    if semester == 1:
        df1 = df1.loc[df1['semester'] == 1]
    elif semester == 2:
        df1 = df1.loc[df1['semester'] == 2]

    x = [i - 0.5 for i in range(1, 7)]

    # Create Semester 1 trace (solid)
    trace = go.Scatter(
        x=x,
        y=df1['fr_diff'].tolist(),
        name='<span style="color: {1}"> {0} </span>'.format(
            course_name, colour),
        text=None,
        textfont={
            'size': 14,
            'color': colour
        },
        line=go.Line(width=3, color=colour, dash=dash_type),
        marker=go.Marker(color=colour, size=10, symbol='diamond'),
        connectgaps=False,
        mode='markers',
        showlegend=showlegend,
        textposition='bottom right',
    )
    return trace
예제 #14
0
def create_remainder_trace(
        df_cdf,
        key,
        size_class,
        area_values,
        count_label,
        is_first
):
    """

    :param df_cdf:
    :param key:
    :param size_class:
    :param area_values:
    :param count_label:
    :param is_first:
    :return:
    """

    area_values = np.add(area_values, 100.0 * df_cdf['y'][:-1])
    scatter = go.Scatter(
        name='%s (%s)' % (size_class['name'], count_label),
        x=100.0 * df_cdf['x'][:-1],
        y=area_values,
        mode='lines',
        fill='tozeroy' if is_first else 'tonexty',
        line=go.Line(
            width=1.0,
            color=size_class['color']
        )
    )

    return area_values, scatter
def plotly_single(ma, average_type, color, label, plot_type='line'):
    """A plotly version of plot_single. Returns a list of traces"""
    summary = list(np.ma.__getattribute__(average_type)(ma, axis=0))
    x = list(np.arange(len(summary)))
    if isinstance(color, str):
        color = list(matplotlib.colors.to_rgb(color))
    traces = [go.Scatter(x=x, y=summary, name=label, line={'color': "rgba({},{},{},0.9)".format(color[0], color[1], color[2])}, showlegend=False)]
    if plot_type == 'fill':
        traces[0].update(fill='tozeroy', fillcolor=color)

    if plot_type in ['se', 'std']:
        if plot_type == 'se':  # standard error
            std = np.std(ma, axis=0) / np.sqrt(ma.shape[0])
        else:
            std = np.std(ma, axis=0)

        x_rev = x[::-1]
        lower = summary - std
        trace = go.Scatter(x=x + x_rev,
                           y=np.concatenate([summary + std, lower[::-1]]),
                           fill='tozerox',
                           fillcolor="rgba({},{},{},0.2)".format(color[0], color[1], color[2]),
                           line=go.Line(color='transparent'),
                           showlegend=False,
                           name=label)
        traces.append(trace)

    return traces
예제 #16
0
 def pcaWiki(self,file):
     self.formDataPCA(file)           
     X_std = StandardScaler().fit_transform(self.X)
     sklearn_pca = sklearnPCA(n_components=2)
     Y_sklearn = sklearn_pca.fit_transform(X_std)
     traces = []
 
     for name in self.names:
         trace = go.Scatter(
             x=Y_sklearn[self.y==name,0],
             y=Y_sklearn[self.y==name,1],
             mode='markers',
             name=name,
             marker=go.Marker(
                 size=12,
                 line=go.Line(
                     color='rgba(217, 217, 217, 0.14)',
                     width=0.5),
                 opacity=0.8))
         traces.append(trace)
     data = go.Data(traces)
     layout = go.Layout(xaxis=go.XAxis(title='PC1', showline=False),
                     yaxis=go.YAxis(title='PC2', showline=False))
     fig = go.Figure(data=data, layout=layout)
     if (self.outputType == 'file'):
         print(py.plot(fig,filename='pca')) 
     else:
         return (py.plot(fig,include_plotlyjs='False',output_type='div')) 
예제 #17
0
 def pca(self,winSize):
     data = np.zeros((len(self.data),len(self.data['FUNC'][winSize])))
     i=0
     for dEl in sorted(self.data):
         self.data[dEl][winSize] = normalizeMaxMin(self.data[dEl][winSize])
         data[i] = self.data[dEl][winSize]
         i+=1
         
     X_std = StandardScaler().fit_transform(np.transpose(data))
     sklearn_pca = sklearnPCA(n_components=2)
     Y_sklearn = sklearn_pca.fit_transform(X_std)
     traces = []
     
     trace = go.Scatter(
         x=Y_sklearn[:,0],
         y=Y_sklearn[:,1],
         mode='markers',
         marker = go.Marker(
             size=12,
             line= go.Line(
                 color='rgba(217, 217, 217, 0.14)',
                 width=0.5),
             opacity=0.8))
     traces.append(trace)
     
     
     data = go.Data(traces)
     layout = go.Layout(xaxis = go.XAxis(title='PC1', showline=False),
                        yaxis = go.YAxis(title='PC2', showline=False))
     fig = go.Figure(data=data, layout=layout)
     if self.outputType=='file':
         print(py.plot(fig, filename='pca.html'))
     else:
         return py.plot(fig, output_type='div')
예제 #18
0
		def get_traces(trace,value,type,color=None,width=.2,opacity=.3):
			if not is_list(value):
				value=[value]*len(trace['y'])
			if values_minus:
				if is_list(values_minus):
					min_value=values_minus
				else:
					min_value=[values_minus]*len(trace['y'])
			else:
				min_value=value
			if 'percent' in type:
				y_up=[trace['y'][_]*(1+value[_]/100.00) for _ in range(len(value))]
				y_down=[trace['y'][_]*(1-min_value[_]/100.00) for _ in range(len(min_value))]
			else:
				y_up=[trace['y'][_]+value[_] for _ in range(len(value))]
				y_down=[trace['y'][_]-min_value[_] for _ in range(len(min_value))]
			y=trace['y']
			upper=go.Scatter(y=y_up,mode='lines',showlegend=False,
							 line=go.Line(width=width),x=trace['x'])
			if 'yaxis' in trace:
				upper['yaxis']=trace['yaxis']
			if color:
				color=normalize(color)
			else:
				if 'color' in trace['line']:
					color=trace['line']['color']
				else:
					color='charcoal'
			upper['line']['color']=color
			lower=upper.copy()
			name=trace['name']+'_' if 'name' in trace else ''
			upper.update(name=name+'upper')
			color=to_rgba(normalize(color),opacity)
			lower.update(fill='tonexty',fillcolor=color,name=name+'lower',y=y_down)
			return upper,lower
예제 #19
0
def create_plot(df):
    grouped_user_ids = df.groupby(df.user_id)
    # data = [
    #
    #
    #     go.Line(
    #         x=df['date_posted'], # assign x as the dataframe column 'x'
    #         y=df['reps']
    #     ),
    #     go.Line(
    #         x=df['date_posted'],  # assign x as the dataframe column 'x'
    #         y=df['reps']
    #     )
    #
    # ]
    data = []
    unique_users = df['user_id'].unique()
    for user in unique_users:
        df_inloop = grouped_user_ids.get_group(user)
        name = User.query.get(user)
        data.append(
            go.Line(name=f'user_id={user}, name ={name.username}',
                    x=df_inloop['date_posted'],
                    y=df_inloop['reps']))

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON
예제 #20
0
def make_ideo_shape(path, line_color, fill_color):
    return dict(
        line=go.Line(color=line_color, width=0.45),
        path=path,
        type="path",
        fillcolor=fill_color,
        layer="below",
    )
예제 #21
0
def graph_draw(sensor_data):
    data = [go.Line(x=list(range(len(sensor_data))), y=sensor_data)]

    layout = plotly.graph_objs.Layout(title='sleeping_pattern_chart')

    figure = plotly.graph_objs.Figure(data=data, layout=layout)

    plotly.offline.plot(figure, filename='sleeping_pattern_chart.html')
예제 #22
0
def create_plot(json_response=False):

    current_date = datetime.date.today()
    starting_date = current_date - datetime.timedelta(days=60)
    all_reals = Real.query.filter_by(
        category="TOTAL CAUSAS SISTEMA RESPIRATORIO").filter(
            and_(Real.date >= starting_date)).all()
    result_real = reals_schema.dump(all_reals)

    end_date = current_date + datetime.timedelta(days=60)
    all_forecasteds = Forecasted.query.filter_by(
        category="TOTAL CAUSAS SISTEMA RESPIRATORIO").filter(
            and_(Forecasted.date >= current_date,
                 Forecasted.date <= end_date)).all()
    result_forecasted = forecasteds_schema.dump(all_forecasteds)

    df_real = pd.DataFrame.from_dict(result_real)
    df_forecasted = pd.DataFrame.from_dict(result_forecasted)

    data = [
        go.Line(
            x=df_real['date'],  # assign x as the dataframe column 'x'
            y=df_real['value'],
            name="Real"),
        go.Line(
            x=df_forecasted['date'],  # assign x as the dataframe column 'x'
            y=df_forecasted['value'],
            name="Estimado")
    ]

    layout = {
        "xaxis": {
            "title": "Fecha"
        },
        "yaxis": {
            "title": "Atenciones por Urgencia Respiratoria"
        }
    }
    fig = dict(data=data, layout=layout)
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    if json_response:
        graphJSON = json.loads(graphJSON)
        return jsonify(graphJSON)
    else:
        return graphJSON
예제 #23
0
def graphRRline(df1):
  df_w1 = df1.loc[df['intervention'] == 'week1']
  df_nw1 = df1.loc[df['intervention'] != 'week1']

  # all traces for plotly
  traces = []

  for i, r in df_w1.iterrows():
    # check for valid colour value
    j = i
    while j > len(colourList)-1:
      j = j-len(colourList)
    edge_trace=go.Scatter(
      x=[1, 2],
      y=[r['w1_drr'], r['w2_drr']],
      text="%s" % r['course_code'],
      line=go.Line(width=2, color=colourList[j]),
      hoverinfo=r['course_code'],
      connectgaps=False,
      mode='lines+markers',
      showlegend=False)
    traces.append(edge_trace)

  title = 'CES course response rate'
  title += '<br>'
  title += '{} '.format('Intervention in Week 1')

  fig = {'data': traces,
         'layout': go.Layout(
           title=title,
           showlegend=True,
           xaxis=dict(
             title='Week',
             range=[0.5, 2.5],
             autotick=False,
             ticks='outside',
             tick0=1,
             dtick=1,
             ticklen=5,
             zeroline=False,
           ),
           yaxis=dict(
             title='Change in response rate (2017-2018)',
             ticklen=5,
             zeroline=True,
             zerolinewidth=4,
           ),
           width=1200,
           height=800,
           hovermode='closest',
           margin=dict(b=50, l=50, r=50, t=50),
           hidesources=True,
         )
         }

  plotly.offline.plot(fig, filename='C:\\Peter\\CoB\\CES Response Rates\\rr.html')
  return fig
예제 #24
0
def make_ribbon(l, r, line_color, fill_color, radius=0.2):
    poligon = ctrl_rib_chords(l, r, radius)
    b, c = poligon
    return dict(line=go.Line(color=line_color, width=0.5),
                path=make_q_bezier(b) + make_ribbon_arc(r[0], r[1]) +
                make_q_bezier(c[::-1]) + make_ribbon_arc(l[1], l[0]),
                type='path',
                fillcolor=fill_color,
                layer='below')
예제 #25
0
def display_linegraphs(selected_values):
    traces = []
    [
        traces.append(
            go.Line(y=(features_log.loc[:, str(val)].values), name=str(val)))
        for val in selected_values
    ]
    layout = go.Layout(legend=dict(orientation="h"))
    return go.Figure(data=traces, layout=layout)
예제 #26
0
def get_reference_trace_for_append(graph_unique_name='', shape_type=''):
    global g_reference_trace_id
    return graph_objs.Scatter(x=[utils.get_base_location_now_date()],
                              y=[0],
                              name=graph_unique_name,
                              text=g_reference_trace_id,
                              mode='none',
                              showlegend=False,
                              line=graph_objs.Line(shape=shape_type))
예제 #27
0
def plot_remainder(
        data: dict,
        key: str,
        label: str,
        is_log: bool = False,
        normal_comparison = True
):
    area_values = np.zeros(len(data['df_expected']['x']) - 1)
    traces = []

    for size_class in cd.shared.SIZE_CLASSES:
        size_data = data['sizes'][size_class['id']]
        track_count = int(size_data['count'])

        area_values, area_trace = create_remainder_trace(
            df_cdf=size_data['df_cdf'],
            key=key,
            area_values=area_values,
            is_first=cd.shared.SIZE_CLASSES.index(size_class) < 1,
            size_class=size_class,
            count_label=locale.format('%d', track_count, grouping=True)
        )
        traces.append(area_trace)

    title = 'Cumulative Remainder of {} Deviations ({} Tracks)'.format(
        label,
        locale.format('%d', data['count'], grouping=True)
    )

    y_axis = {'title': 'Population Remaining (%)'}
    if is_log:
        y_axis['title'] = 'Log {}'.format(y_axis['title'])
        y_axis['type'] = 'log'

    if normal_comparison:
        traces.append(go.Scatter(
            name='Normal Threshold',
            x=100.0 * data['df_expected']['x'],
            y=data['df_expected']['y'],
            mode='lines',
            line=go.Line(
                color='rgba(0, 0, 0, 0.75)',
                dash='dash',
                width=1.0
            )
        ))

    cd.display.plotly(
        data=traces,
        layout=make_layout(
            data,
            title=title,
            fixed=True,
            y_axis=y_axis
        )
    )
예제 #28
0
def update_graph(selected_options):
    data = []
    for symbol in selected_options:
        history = get_history(symbol, 180)
        #log.debug(type(history))
        data.append(go.Line(x=history.index, y=history['close'], text=symbol))

#    log.debug(history)

    return {'data': data, 'layout': go.Layout(yaxis={'title': 'Close Price'})}
예제 #29
0
def update_graph(type1):
    if type1 == 'All':
        masks = data1['detected_state'].value_counts().reset_index()
        return {
            'data': [go.Line(x=masks['index'], y=masks['detected_state'])],
            'layout':
            go.Layout(title='Number of Patients',
                      xaxis={'title': 'Number of Patients'},
                      yaxis={'title': 'states'})
        }
    else:
        status = data1[data1['current_status'] == type1]
        mask4 = status['detected_state'].value_counts().reset_index()
        return {
            'data': [go.Line(x=mask4['index'], y=mask4['detected_state'])],
            'layout':
            go.Layout(title='Number of Patients',
                      xaxis={'title': 'Number of patients'},
                      yaxis={'title': 'States'})
        }
예제 #30
0
def history_plotly(hist):
    init_notebook_mode(connected=True)

    loss = []
    val_loss = []
    acc = []
    val_acc = []

    for history_temp in hist:
        loss += history_temp['loss']
        val_loss += history_temp['val_loss']
        acc += history_temp['acc']
        val_acc += history_temp['val_acc']

    iplot([
        go.Line(y=loss, name='loss'),
        go.Line(y=val_loss, name='val_loss'),
        go.Line(y=acc, name='acc'),
        go.Line(y=val_acc, name='val_acc')
    ],
          show_link=False)