示例#1
0
    def create_figures(stats: List[Stat], name: str) -> List[go.FigureWidget]:
        if name == "Categories":
            data = Result.build_stack_bar_data(stats)
            layout = Result.get_layout("Category fields", len(stats))
            layout.barmode = "stack"
            return [go.FigureWidget(data, layout)]
        figures = []
        for stat in stats:
            y = stat.index.values.astype(str)
            if isinstance(stat, pd.Series):
                data = [
                    go.Bar(x=stat.values, y=y, orientation="h", opacity=0.7)
                ]
            else:
                data = [
                    go.Bar(x=stat[c].values,
                           y=y,
                           orientation="h",
                           opacity=0.7,
                           name=c) for c in stat.columns
                ]

            layout = Result.get_layout(stat.name, len(stat))
            layout.xaxis = go.layout.XAxis(
                range=[0, max(stat.values.max(), 1) * 1.05])
            if stat.name.startswith("Coverage"):
                layout.xaxis.tickformat = ".2p"
            if stat.name == "Coverage for boolean fields":
                layout.barmode = "stack"
            if stat.name.startswith("Fields coverage"):
                layout.annotations = Result.make_annotations(stat)

            figures.append(go.FigureWidget(data, layout))
        return figures
def prediction():
    input1 = st.text_input("Enter Tweet", "Type here")

    if st.button("Predict"):
        process1 = url(input1)
        process2 = smiley(process1)
        process3 = lower(process2)
        process4 = decontracted(process3)
        process5 = digit(process4)
        process6 = punct(process5)
        process7 = odd(process6)
        process8 = space(process7)
        process9 = stop(process8)
        process10 = space(process9)
        process11 = [process10]
        vect_pro = vectorizer.transform(process11)
        result1 = vect_pro.reshape(1, -1)
        result = model.predict(result1)

        if result == 1:
            st.success('The tweet is Positive')

            graph = model.predict_proba(result1)[:, 1]
            a = graph.tolist()
            b = (a[0])
            c = (1 - a[0])
            value = [b, c]
            labels = ['Positive', 'Negative']
            values = [c, b]
            colors = ['rgb(26,152,80)', 'rgb(120,14,40)']
            trace = go.Pie(labels=labels,
                           values=value,
                           textfont=dict(size=20),
                           marker=dict(colors=colors))
            fig = go.FigureWidget(data=[trace])
            st.plotly_chart(fig)

        if result == 0:
            st.error('The tweet is Negative')

            graph = model.predict_proba(result1)[:, 1]
            a = graph.tolist()
            b = (a[0])
            c = (1 - a[0])
            values = [b, c]
            labels = ['Negative', 'Positive']
            values = [c, b]
            colors = ['rgb(120,14,40)', 'rgb(26,152,80)']
            trace = go.Pie(labels=labels,
                           values=values,
                           textfont=dict(size=20),
                           marker=dict(colors=colors))
            fig = go.FigureWidget(data=[trace])
            st.plotly_chart(fig)
示例#3
0
def ipy_plot_interactive(df, opacity=.3):
    '''Interactive plotly widget for a cryoDRGN pandas dataframe'''
    import plotly.graph_objs as go
    from ipywidgets import interactive
    if 'labels' in df.columns:
        text = [f'Class {k}: index {i}' for i,k in zip(df.index, df.labels)] # hovertext
    else:
        text = [f'index {i}' for i in df.index] # hovertext
    
    xaxis, yaxis = df.columns[0], df.columns[1]
    f = go.FigureWidget([go.Scattergl(x=df[xaxis],
                                  y=df[yaxis],
                                  mode='markers',
                                  text=text,
                                  marker=dict(size=2,
                                              opacity=opacity,
                                              color=np.arange(len(df)),
                                              colorscale='hsv'
                                             ))])
    scatter = f.data[0]
    N = len(df)
    f.update_layout(xaxis_title=xaxis, yaxis_title=yaxis)
    f.layout.dragmode = 'lasso'

    def update_axes(xaxis, yaxis, color_by, colorscale):
        scatter = f.data[0]
        scatter.x = df[xaxis]
        scatter.y = df[yaxis]
        
        scatter.marker.colorscale = colorscale
        if colorscale is None:
            scatter.marker.color = None
        else:
            scatter.marker.color = df[color_by] if color_by != 'index' else df.index
        with f.batch_update(): # what is this for??
            f.layout.xaxis.title = xaxis
            f.layout.yaxis.title = yaxis
 
    widget = interactive(update_axes, 
                         yaxis=df.select_dtypes('number').columns, 
                         xaxis=df.select_dtypes('number').columns,
                         color_by = df.columns,
                         colorscale = [None,'hsv','plotly3','deep','portland','picnic','armyrose'])

    t = go.FigureWidget([go.Table(
                        header=dict(values=['index']),
                        cells=dict(values=[df.index]),
                        )])

    def selection_fn(trace, points, selector):
        t.data[0].cells.values = [df.loc[points.point_inds].index]

    scatter.on_selection(selection_fn)
    return widget, f, t
示例#4
0
 def create_figure(self):
     self.filter_data()
     data = []
     title = self.generate_title()
     xaxis_name = self.options.get('xaxis_name',
                                   'Probability of Compliance (%)')
     yaxis_name = self.options.get('yaxis_name',
                                   'Difference in EC (micromhos/cm)')
     layout = go.Layout(template='seaborn',
                        title=dict(text=title),
                        yaxis=dict(zeroline=True,
                                   zerolinecolor='#000000',
                                   title=yaxis_name,
                                   rangemode='tozero'),
                        xaxis=dict(title=xaxis_name)
                        )
     results = {'Scenario': [],
                '# of Days Standards are Applicable': [],
                '# of Days Violated': [],
                r'% of Days Violated': []}
     for case in self.cases:
         mask = (self.df_to_plot[self.colname_case] == case)
         yval = self.df_to_plot[mask][self.colname_y].sort_values(
             ascending=True)
         n = yval.count()
         xval = np.arange(1, n + 1) / n * 100.
         name = case
         data.append(go.Scatter(x=xval,
                                y=yval.values,
                                name=case))
         results['Scenario'].append(case)
         results['# of Days Standards are Applicable'].append(n)
         n_violated = yval[yval > 0.].count()
         results['# of Days Violated'].append(n_violated)
         results[r'% of Days Violated'].append(
             f'{n_violated / n * 100.:.2f}')
     self.fig = go.FigureWidget(data=data, layout=layout)
     self.df_results = pd.DataFrame(data=results)
     self.results = go.FigureWidget(data=[go.Table(
         header=dict(values=[[v] for v in self.df_results.columns]),
         cells=dict(values=[self.df_results[k] for k in self.df_results.columns],
                    height=30))],
         layout=go.Layout(
             template='seaborn',
             height=(self.df_results.shape[0] + 2) * 20 + 100,
             margin=dict(t=30, b=10),
             font=dict(size=14)
     ))
示例#5
0
def slider_histo(data):
    import plotly.graph_objs as go
    import plotly.figure_factory as ff

    #     data  = [30.2049, 51.3693, 51.8094, 30.5573, 56.8151, 45.9166, 56.2858, 55.4125, 72.8778,
    #              39.7996, 34.8203, 36.8362, 39.9959, 54.7995, 52.5158, 40.6841, 61.3939, 48.5818,
    #              41.4944, 71.5607, 49.0913, 57.7985, 70.2787, 45.2226, 55.7449, 69.0475, 33.9624,
    #              51.3384, 53.1948, 46.1682, 66.5202, 37.0265, 48.0182, 44.2164, 56.9336, 69.7961,
    #              48.6728, 44.5923, 33.2164, 41.8337,56.7741, 35.6030, 33.9237, 41.5178, 50.4453,
    #              29.0570, 33.0124, 58.6281, 39.2005, 42.9119]

    hist_data = [data]
    group_labels = ['distplot']
    f = ff.create_distplot(hist_data,
                           group_labels,
                           bin_size=1,
                           show_rug=True,
                           show_curve=False)
    fig = go.FigureWidget(f)
    fig.data[0].marker.line = dict(color='black', width=2)
    fig.data[1].line.color = 'red'
    fig.layout.sliders = [
        dict(active=0,
             currentvalue={"prefix": "bin size: "},
             pad={"t": 20},
             steps=[
                 dict(label=i, method='restyle', args=['xbins.size', i])
                 for i in range(1, 100)
             ])
    ]
    fig.show()
示例#6
0
 def build_graph(self):
     xrange = [min(self.nodes.x) - 50, max(self.nodes.x) + 50]
     yrange = [min(self.nodes.y) - 30, max(self.nodes.y) + 30]
     self.graph = go.FigureWidget(
         data=[self.edges, self.nodes, self.node_select, self.node_status],
         layout=dict(
             width=500,
             height=350,
             margin=dict(b=20, l=5, r=5, t=40),
             xaxis=dict(range=xrange,
                        showgrid=False,
                        zeroline=False,
                        showticklabels=False),
             yaxis=dict(range=yrange,
                        showgrid=False,
                        zeroline=False,
                        showticklabels=False),
             showlegend=False,
             plot_bgcolor='white',
         ),
     )
     # need to reassign pointers because FigureWidget makes a copy...
     self.edges = self.graph.data[0]
     self.nodes = self.graph.data[1]
     self.node_select = self.graph.data[2]
     self.node_status = self.graph.data[3]
def get_ratiometric_reading_plot():
    """ Quick plot of a spatial ratiometric optical reading over a range of temperatures and DO values. """
    temperatures_to_plot = TEMPERATURE_DOMAIN[::5]

    return go.FigureWidget(
        [
            go.Scatter(
                x=DO_DOMAIN,
                y=simulate_spatial_ratiometric_reading(DO_DOMAIN, temperature),
                mode="lines",
                line={
                    "color": color_from_temperature(temperature),
                    "width": 1
                },
                name=f"T={temperature}",
            ) for temperature in temperatures_to_plot
        ],
        layout={
            "title": "spatial ratiometric reading over DO and temperature",
            "xaxis": {
                "title": "DO (mmHg)"
            },
            "yaxis": {
                "title": "Spatial Ratiometric Reading (unitless)"
            },
        },
    )
示例#8
0
    def build_summary(self,Fit1DWidgets):
        y = []
        yerr = []
        for i,wavelength in enumerate(self.wavelengths):
            y.append(Fit1DWidgets[wavelength].get_fit_param('center').value)
            yerr.append(Fit1DWidgets[wavelength].get_fit_param('center').stderr)
        
        self.summary = go.FigureWidget()
        self.summary.add_scatter(y=y,error_y={'array':yerr})
        
        yval = 0.1076
        self.summary.add_shape( 
            xref='paper', x0=0, x1=1, y0=yval, y1=yval, line=dict(dash='dash'))
        
        
        for pct in [0.5,1]:
            for sign in [1.0,-1.0]:
                yval = 0.1076*(1.00+sign*pct/100)
                self.summary.add_shape(
                    xref='paper', x0=0, x1=1, y0=yval, y1=yval, line=dict(dash='dot',color='red') 
                )

        self.summary.add_annotation(x=0.5,y=0.1076*(1.00-0.5/100),text='0.5% Error')
        self.summary.update_layout(
            xaxis_title = 'Wavelength',
            yaxis_title = 'AgBeh Peak q',
            xaxis=dict(
                tickmode='array',
                tickvals=[i for i,_ in enumerate(self.wavelengths)],
                ticktext=self.wavelengths,
            )
        )
def calibration_error_plot(predicted_do, actual_do, temperature, fit_title):
    """ Plot showing the error in predicted DO as distributed over DO and temperature """
    return go.FigureWidget(
        data=[
            go.Scatter(
                x=actual_do,
                y=predicted_do - actual_do,
                mode="markers",
                text=[f"T={T}" for T in temperature],
                marker=dict(
                    color=temperature,
                    symbol="circle-open",
                    colorscale="Bluered",
                    cmin=TEMPERATURE_STANDARD_OPERATING_MIN,
                    cmax=TEMPERATURE_STANDARD_OPERATING_MAX,
                ),
            )
        ],
        layout=go.Layout(
            title=f"DO error in {fit_title}",
            xaxis={
                "title": "Dissolved Oxygen (mmHg)",
                "range": [0, DO_MAX_MMHG]
            },
            yaxis={"title": "DO error (predicted - actual)<br>(mmHg)"},
            hovermode="closest",
            shapes=DO_AXIS_ERROR_BOUNDS_LINES,
        ),
    )
示例#10
0
def overlay_dr_spectrum(
    dataframe, progressions, freq_col="Frequency", int_col="Intensity", **kwargs
):
    layout = define_layout("Frequency (MHz)", "Intensity")
    fig = go.FigureWidget(layout=layout)

    fig.add_scattergl(
        x=dataframe[freq_col], y=dataframe[int_col], name="Observation", opacity=0.4
    )

    colors = generate_colors(len(progressions), cmap=plt.cm.tab10)
    level = 2.0

    for index, (progression, color) in enumerate(zip(progressions, colors)):
        mask = np.where(progression <= np.max(dataframe[freq_col]))
        progression = progression[mask]
        indices = np.array(
            [routines.find_nearest(dataframe[freq_col], freq) for freq in progression]
        )
        indices = indices[:, 1]
        y = dataframe[int_col].iloc[indices] * 1.2
        fig.add_scattergl(
            x=progression,
            y=y,
            marker={"color": color},
            mode="markers+lines",
            hoverinfo="name+x",
            name="Progression {}".format(index),
        )
    return fig
示例#11
0
def create_display(c: Union[pd.DataFrame, Dict[str, pd.DataFrame], go.Figure]):
    """ different kinds of display in jupyter notebook """
    if isinstance(c, pd.DataFrame):
        return display_table(c)
    if isinstance(c, go.Figure):
        return display(go.FigureWidget(c))
    return display(c)
示例#12
0
    def __init__(self,
                 title_str=None,
                 ch_names=None,
                 shot_noise=False,
                 legend_orientation=None):
        """ MultiTraceFig constructor

        :param title_str: string to display for plot title
        :param ch_names: list of channel name strings for multi
            -channel plot
        :param shot_noise: boolean of whether or not to plot
            shot noise on individual traces
        """

        self._fig = go.FigureWidget(data=[])
        self._shot_noise = shot_noise
        self._ch_names = ch_names

        if self._ch_names is not None:

            # Initialize all channels if given
            self._num_ch = 0
            self._allocate_arrays()

        else:
            self._num_ch = 0

        if title_str is not None:
            self._fig.layout.update(title=title_str)

        if legend_orientation is not None:
            self._fig.update_layout(legend=dict(x=0, y=1.1),
                                    legend_orientation=legend_orientation)
示例#13
0
    def __init__(self,
                 x,
                 y,
                 u,
                 v,
                 scale=0.1,
                 arrow_scale=0.3,
                 angle=math.pi / 9,
                 scaleratio=None,
                 **kwargs):
        super(Quiver, self).__init__()

        if scaleratio is None:
            self.quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle)
        else:
            self.quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle,
                                      scaleratio)
        barb_x, barb_y = self.quiver_obj.get_barbs()
        arrow_x, arrow_y = self.quiver_obj.get_quiver_arrows()

        plt = go.Scatter(x=barb_x + arrow_x,
                         y=barb_y + arrow_y,
                         mode="lines",
                         **kwargs)
        self.fig = go.FigureWidget(
            go.Figure(data=[plt], layout=vis_plot.layout_default()))
示例#14
0
    def create_figure(self, number_traces):
        self.traces = []

        self.fig = go.FigureWidget(
            tools.make_subplots(rows=number_traces, cols=1, print_grid=False))

        for i in range(1, number_traces + 1):
            self.traces.append([])

            for _ in range(len(self.scan_names)):
                trace = go.Scatter(
                    x=[],
                    y=[],  # Data
                    mode='lines+markers',
                    name='f' + str(i),
                    showlegend=True)

                diff_trace = go.Scatter(
                    x=[],
                    y=[],  # Data
                    mode='lines+markers',
                    name='df' + str(i),
                    showlegend=True)

                diff_diff_trace = go.Scatter(
                    x=[],
                    y=[],  # Data
                    mode='lines+markers',
                    name='ddf' + str(i),
                    showlegend=True)

                self.traces[i - 1].append(trace)
                self.fig.append_trace(
                    trace, i, 1)  # using i + 1 because plot index starts at 1
                self.fig.append_trace(
                    diff_trace, i,
                    1)  # using i + 1 because plot index starts at 1
                self.fig.append_trace(
                    diff_diff_trace, i,
                    1)  # using i + 1 because plot index starts at 1

                self.fig['data'][3 * (i - 1) + 1].update(
                    yaxis="y" + str(number_traces + i * 2))
                self.fig['data'][3 * (i - 1) + 2].update(
                    yaxis="y" + str(number_traces + i * 2 + 1))

                self.fig['layout']['yaxis' +
                                   str(number_traces + i * 2)] = dict(
                                       overlaying="y" + str(i),
                                       anchor="x" + str(i),
                                       side="right")
                self.fig['layout']['yaxis' +
                                   str(number_traces + i * 2 + 1)] = dict(
                                       overlaying="y" + str(i),
                                       anchor="x" + str(i),
                                       side="right")

        self.fig['layout'].update(title='Scan',
                                  plot_bgcolor='rgb(230, 230, 230)')
        self.fig_box.children = (self.fig, )
示例#15
0
def adj_plot_hist(pred,
                  initial_bin_width=3):  # missing the mean simple line plot
    pop_mean = [pred.mean()] * len(pred)
    figure_widget = go.FigureWidget(data=[
        go.Histogram(x=pred, xbins={"size": initial_bin_width}, name='Bin'),
        go.Scatter(x=pred[0:], y=pop_mean, mode='lines', name='Predictor Mean')
    ])

    bin_slider = widgets.FloatSlider(
        value=initial_bin_width,
        min=0,
        max=pred.max(),
        step=pred.max() / 20,
        description="Bin width:",
        readout_format=".1f",  # display as integer
    )

    histogram_object = figure_widget.data[0]

    def set_bin_size(change):
        histogram_object.xbins = {"size": change["new"]}

    bin_slider.observe(set_bin_size, names="value")

    output_widget = widgets.VBox([figure_widget, bin_slider])
    return output_widget
示例#16
0
 def _create_kde_figure(self, col, bw_method=None, *, selection=None):
     if col in self._figures_kde:
         self._update_kde_figure(col, selection=selection)
     else:
         if selection is None:
             selection = self.box.inside(self.data)
         x_points, y_base, y_select = self._compute_kde(
             col, selection, bw_method)
         fig = go.FigureWidget(
             data=[
                 go.Scatter(
                     x=x_points,
                     y=y_base,
                     name='Overall',
                     fill='tozeroy',
                     marker_color=colors.DEFAULT_BASE_COLOR,
                 ),
                 go.Scatter(
                     x=x_points,
                     y=y_select,
                     name='Inside',
                     fill='tozeroy',  #fill='tonexty',
                     marker_color=colors.DEFAULT_HIGHLIGHT_COLOR,
                 ),
             ],
             layout=dict(
                 showlegend=False,
                 margin=dict(l=10, r=10, t=10, b=10),
                 yaxis_showticklabels=False,
                 **styles.figure_dims,
             ),
         )
         fig._figure_kind = 'kde'
         self._figures_kde[col] = fig
示例#17
0
def apply(x,y,fig_type,l_op,t_op,color='#fff',flip=False):
	f=go.FigureWidget()
	fig=call_function(x,y,fig_type,color='rgb(255,255,255)',z='def')
	f.add_trace(fig['data'][0])
	f.layout=fig['layout']
	x = pd.Series(np.array(x))
	y = pd.Series(np.array(y))
	df = pd.concat([x, y],axis=1)

	if flip==True:
		df, f = flip_axes(x, y)

	for l,op in zip(l_op,t_op):
		if l=='agg':
			if op=='mean':
			    f.plotly_restyle({'x':[list(df.groupby([0]).mean().index)],'y':[list(df.groupby([0]).mean()[1])]})
			if op=='max':
			    f.plotly_restyle({'x':[list(df.groupby([0]).max().index)],'y':[list(df.groupby([0]).max()[1])]})
			if op=='mode':
			    f.plotly_restyle({'x':[list(df.groupby([0]).mode().index)],'y':[list(df.groupby([0]).mode()[1])]})
			if op=='sum':
			    f.plotly_restyle({'x':[list(df.groupby([0]).sum().index)],'y':[list(df.groupby([0]).sum()[1])]})
			if op=='min':
			    f.plotly_restyle({'x':[list(df.groupby([0]).min().index)],'y':[list(df.groupby([0]).min()[1])]})
			if op=='stddev':
			    f.plotly_restyle({'x':[list(df.groupby([0]).std().index)],'y':[list(df.groupby([0]).std()[1])]})
			if op=='count':
			    f.plotly_restyle({'x':[list(df.groupby([0]).count().index)],'y':[list(df.groupby([0]).count()[1])]})
		elif l=='rng':
			f.plotly_relayout({'yaxis.range':[op[0],op[1]]})
	po.plot(f,auto_open=False,filename='dash10/templates/dash10/plots/plot1.html')
	return 'plot1.html'
示例#18
0
    def plot(self, phase=None, pos=None, name=None):
        """ On ajoute à l'affichage de l'Opset une sélection d'instants."""
        f = make_subplots(rows=1, cols=1, specs=[[{"type": "scatter"}]])
        f = go.FigureWidget(f)
        e = self.make_figure(f, phase, pos, name)
        out = widgets.interactive(e['update_function'],
                                  colname=e['variable_dropdown'],
                                  sigpos=e['signal_slider'])

        bxplot = widgets.VBox([
            widgets.HBox([
                e['variable_dropdown'], e['previous_button'], e['next_button']
            ]),
            widgets.HBox([f, e['signal_slider']])
        ])
        # Pour info :
        # f = tabs.children[0].children[1].children[0]

        bxlearn = widgets.VBox([
            e['progress_bar'],
            widgets.HBox([
                widgets.VBox([e['variable_selection'], e['learn_button']]),
                widgets.VBox([e['factor_selection'], e['message_label']])
            ])
        ])

        bxparam = self.param()

        tabs = widgets.Tab(children=[bxplot, bxparam, bxlearn])
        tabs.set_title(0, "Plot")
        tabs.set_title(1, "Param")
        tabs.set_title(2, "Learn")
        return tabs
示例#19
0
    def plotlyIsosurface(self, isomin, isomax, title):
        '''Return a plotly FigureWidget containing an isosurface representation of the 3D histogram
        
        Args: 
            isomin (int): minimum value of isosurface colorscale
            isomax (int): max value of isosurface colorscale
            title (string): title of the plot
        '''

        # generate X, Y, Z, Values arrays. Plotly needs these as inputs to the Isosurface function. We are storing these as properties
        # so that the user could access them to plot more involved isosurface representations from the Jupyter notebook.
        self.histo3D_unrolled = np.reshape(self.histo3D[0], [-1])
        self.histo3D_unrolled_coords = [[x, y, z]
                                        for z in self.histo3D[1][2][:-1]
                                        for y in self.histo3D[1][1][:-1]
                                        for x in self.histo3D[1][0][:-1]]

        data = [
            go.Isosurface(x=np.array(self.histo3D_unrolled_coords)[:, 0],
                          y=np.array(self.histo3D_unrolled_coords)[:, 1],
                          z=np.array(self.histo3D_unrolled_coords)[:, 2],
                          value=self.histo3D_unrolled,
                          isomin=isomin,
                          isomax=isomax,
                          colorscale='Blues')
        ]
        layout = go.Layout(title=title)
        return go.FigureWidget(data, layout)
示例#20
0
    def show_plot(coord_x=field_list[0], coord_y=field_list[1], coord_z=field_list[2], coord_color=field_list[3]):
        fig = build_plotly_scatter3d(data, field_list, coord_x, coord_y, coord_z, coord_color, None, None)
        fig.update_layout(height=500)
        widget = go.FigureWidget(fig)

        out = Output()

        @out.capture(clear_output=True)
        def handle_click(trace, points, state):
            try:
                selected_number = points.point_inds[0]
                point = data[selected_number]
                res = tabulate.tabulate([i for i in point.items()], floatfmt=".2f")
                print("Selected:\n" + res)


                size = [15]*len(data)
                symbol = ['circle']*len(data)

                if selected_number is not None:
                    size[selected_number] = 25
                    symbol[selected_number] = 'diamond'

                with widget.batch_update():
                    widget.data[0].marker.size = size
                    widget.data[0].marker.symbol = symbol
            except:
                pass

        widget.data[0].on_click(handle_click)

        display(HBox([widget, out]))
示例#21
0
 def selection_feature_scores(self):
     try:
         scores = self._compute_selection_feature_scores().data.iloc[0]
     except KeyboardInterrupt:
         raise
     except:
         scores = {}
     y = self.scope.get_parameter_names(False)
     x = [scores.get(yi, numpy.nan) for yi in y]
     fmt = lambda x: x if isinstance(x, str) else "{:.3f}".format(x)
     t = [fmt(scores.get(yi, "N/A")) for yi in y]
     fig = go.FigureWidget(go.Bar(
         x=x,
         y=y,
         text=t,
         orientation='h',
         textposition='outside',
         texttemplate='%{text}',
         marker_color=colors.DEFAULT_HIGHLIGHT_COLOR,
     ),
                           layout=dict(
                               margin=dict(t=0, b=0, l=0, r=0),
                               height=len(x) * 22,
                               yaxis_autorange="reversed",
                           ))
     self._selection_feature_score_fig = fig
     return fig
def _plot_chord_diagram_for_raw_bugs(project_name: str,
                                     project_repo: pygit2.Repository,
                                     bug_set: tp.FrozenSet[PygitBug],
                                     szz_tool: str) -> gob.FigureWidget:
    """Creates a chord diagram representing relations between introducing/fixing
    commits for a given set of RawBugs."""

    # maps commit hex -> node id
    map_commit_to_id: tp.Dict[pygit2.Commit,
                              int] = _map_commits_to_nodes(project_repo)
    commit_type: tp.Dict[pygit2.Commit, NodeType] = {}
    commit_count = len(map_commit_to_id.keys())

    edge_colors = ['#d4daff', '#84a9dd', '#5588c8', '#6d8acf']

    for commit in project_repo.walk(project_repo.head.target.id,
                                    pygit2.GIT_SORT_TIME):
        commit_type[commit] = NodeType.DEFAULT

    # if less than 2 commits, no graph can be drawn!
    if commit_count < 2:
        raise PlotDataEmpty

    commit_coordinates = _compute_node_placement(commit_count)

    # draw relations and preprocess commit types
    lines = _generate_line_data(bug_set, commit_coordinates, map_commit_to_id,
                                commit_type, edge_colors)
    nodes = _generate_node_data(project_repo, commit_coordinates,
                                map_commit_to_id, commit_type)

    data = nodes + lines
    layout = _create_layout(f'{szz_tool} {project_name}')
    return gob.FigureWidget(data=data, layout=layout)
示例#23
0
    def __init__(self, sample_frequency, number_samples, centre_frequency,
                 title, height, width):
        """SpectrumPlot constructor
        """

        self._centre_frequency = centre_frequency
        self._sample_frequency = sample_frequency
        self._number_samples = number_samples

        self._data = go.Scatter(
            x=np.arange(-self._sample_frequency / 2, self._sample_frequency /
                        2, self._sample_frequency / self._number_samples) +
            self._centre_frequency,
            y=np.zeros(self._number_samples),
            name='Spectrum')

        self._plot = go.FigureWidget(data=self._data,
                                     layout={
                                         'title': title,
                                         'height': height,
                                         'width': width,
                                         'xaxis': {
                                             'title': 'Frequency (Hz)'
                                         },
                                         'yaxis': {
                                             'title':
                                             ''.join(['Amplitude (dB)']),
                                             'range': [-200, -60]
                                         }
                                     })
示例#24
0
def get_optical_reading_plot():
    """Quick plot of a single-patch optical reading over a range of temperatures and DO values, using
    a precalculated, hardcoded fit.
    """
    temperatures_to_plot = TEMPERATURE_DOMAIN[::5]

    return go.FigureWidget(
        [
            go.Scatter(
                x=DO_DOMAIN,
                y=get_optical_reading_normalized(DO_DOMAIN, temperature),
                mode="lines",
                line={
                    "color": color_from_temperature(temperature),
                    "width": 1
                },
                name=f"T={temperature}",
            ) for temperature in temperatures_to_plot
        ],
        layout={
            "title": "Normalized optical reading from a patch",
            "xaxis": {
                "title": "DO (mmHg)"
            },
            "yaxis": {
                "title": "Optical reading (normalized max=1/min=0)"
            },
        },
    )
示例#25
0
    def __init__(self, width="col-md-2", height="small"):
        self.fig = go.FigureWidget()

        self.fig.add_pie(
            hole=1,
            values=[100],
            hoverinfo="none",
            textinfo="none",
        )

        self.fig.layout = go.Layout(
            showlegend=False,
            autosize=False,
            height=self.MODE_CELL_HEIGHT[height],
            width=self.MODE_CELL_WIDTH[width],
            margin={
                "l": 0,
                "r": 0,
                "t": 0,
                "b": 0
            },
            paper_bgcolor="rgba(0,0,0,0)",
            plot_bgcolor="rgba(0,0,0,0)",
            annotations=[],
        )
示例#26
0
def make_scatter(products_df, xcol, ycol, hovercol, tickprefix=''):
    f_scatter = go.FigureWidget([
        go.Scatter(x=products_df[xcol],
                   y=products_df[ycol],
                   mode='markers',
                   text=[x[:30] for x in products_df[hovercol]],
                   selected_marker_size=5,
                   marker_size=3,
                   selected_marker_color='red',
                   opacity=.8)
    ])
    scatter = f_scatter.data[0]

    N = len(products_df)
    scatter.x = scatter.x + np.random.rand(N) / 100 * (
        products_df[xcol].max() - products_df[xcol].min())
    scatter.y = scatter.y + np.random.rand(N) / 100 * (
        products_df[ycol].max() - products_df[ycol].min())
    scatter.selectedpoints = list(range(N))

    f_scatter.update_layout(xaxis_title=xcol,
                            yaxis_title=ycol,
                            xaxis_tickprefix=tickprefix,
                            plot_bgcolor="#FFFFFF",
                            xaxis_linecolor="#BCCCDC",
                            yaxis_linecolor="#BCCCDC",
                            xaxis_fixedrange=True,
                            yaxis_fixedrange=True,
                            dragmode="select",
                            clickmode="select")
    return f_scatter
示例#27
0
def display_gantt_chart(G, begin=None, colors=None, reverse_colors=False, index_col='Type',
                        show_colorbar=True, title=None, bar_width=0.2, showgrid_x=True,
                        showgrid_y=True, group_tasks=True):
    """
    This function displays a Gantt chart representation
    of the dependency network
    """
    # If a begin date is not provided, use the begin date of G
    if begin is None:
        begin = G.graph['Begin']
        
    # Convert date string into datetime format
    begin = datetime.strptime(begin, '%Y-%m-%d').date()
    
    # If a title is not provided, use the title of G
    if title is None:
        title = G.graph['Title']
        
    # Convert graph G into a dataframe format that ff.create_gantt() can read
    df = to_dataframe(G, begin, index_col)
    
    # Create Gantt chart
    fig = ff.create_gantt(df, colors=colors, reverse_colors=reverse_colors, index_col=index_col,
                          show_colorbar=show_colorbar, title=title, bar_width=bar_width,
                          showgrid_x=showgrid_x, showgrid_y=showgrid_y, group_tasks=group_tasks)
    
    # Convert Gantt chart into a figure widget and display it
    f = go.FigureWidget(fig)
    display(f)
示例#28
0
def score_table(quality_estimation, field_accuracy) -> go.FigureWidget:
    cells = [
        ["<b>Field Accuracy Score</b>", "<b>Overall Quality Score</b>"],
        [
            "<b>" + str(field_accuracy) + "<b>",
            "<b>" + str(quality_estimation) + "</b>"
        ],
    ]

    font = dict(color="black", size=20)
    trace = go.Table(
        header=dict(values=[cells[0][0], cells[1][0]],
                    fill=dict(color="gray"),
                    font=font),
        cells=dict(
            values=[cells[0][1:], cells[1][1:]],
            fill=dict(color=[[get_color(quality_estimation)]]),
            font=font,
        ),
    )

    layout = go.Layout(autosize=True,
                       margin=dict(l=0, t=25, b=25, r=0),
                       height=150)
    return go.FigureWidget(data=[trace], layout=layout)
示例#29
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._thedata = self._vizapp.get_data('mean-spatial-flux')

        self._theoverlay = None

        # Slice slider
        self._slice_slider = IntSlider(description='Slice #:', max=10)
        self._slice_slider.observe(self._slice_slider_on_value_change)

        # TODO: refactor this
        self._slice_slider.max = self._thedata.shape[0]

        # Data selector
        self._data_dropdown = Dropdown(description='Data:', options=self._vizapp._1d_data.keys(), multi=True)
        self._data_dropdown.observe(self._data_dropdown_on_change)

        # Overlay selector
        self._overlay_dropdown = Dropdown(description='Overlay:', options=['None'] + list(self._vizapp._1d_data.keys()))
        self._overlay_dropdown.observe(self._overlay_dropdown_on_change)

        # Processing selector
        self._processing_dropdown = Dropdown(description='Processing:', options=['Select...'] + list(self._vizapp.get_1d_processing()))
        self._processing_dropdown.observe(self._processing_dropdown_on_change)
        self._processing_vbox = VBox([])

        self._show_plot()

        self._fig = go.FigureWidget(self._gofig)

        self._line1 = HBox([self._data_dropdown, self._overlay_dropdown])
示例#30
0
def plot_line(df,
              y,
              fig=None,
              color='#FF5949',
              domain=dict(x=[0, 1]),
              name=None):
    fig = go.FigureWidget() if fig is None else fig
    fig.layout.template = 'plotly_dark'
    if type(df) == list:
        for i, d in enumerate(df):
            fig.add_trace(
                go.Scatter(x=d.index,
                           y=d[y],
                           marker=dict(color=color[i]),
                           name=name[i],
                           hoverinfo='y'))
            # fig.add_trace(go.Scatter(x=d.index, y=d[y], marker=dict(color=color[i]), domain=domain, name=name[i], hoverinfo='y'))
    else:
        fig.add_trace(
            go.Scatter(x=df.index,
                       y=df[y],
                       marker=dict(color=color),
                       name=name))
        # fig.add_trace(go.Scatter(x=df.index, y=df[y], marker=dict(color=color), domain=domain, name=name))
    return fig