Exemplo n.º 1
0
def update_correlation_plot_bis(*args):
    handler_1 = handler_list[args[14]]
    handler_2 = handler_list[args[15]]

    param_list_1 = handler_1.get_param_list()
    param_dict_1 = {}
    for i in range(len(param_list_1)):
        param_dict_1[param_list_1[i]] = args[i]
    print(param_list_1)
    data_1 = handler_1.get_data(param_dict_1)
    if 'log10' in args[6]:
        data_1 = np.log10(data_1)

    param_list_2 = handler_2.get_param_list()
    param_dict_2 = {}
    for i in range(len(param_list_2)):
        param_dict_2[param_list_2[i]] = args[i + 7]
    data_2 = handler_2.get_data(param_dict_2)
    if 'log10' in args[13]:
        data_2 = np.log10(data_2)

    # make plot
    data_1 = data_1.flatten()
    data_2 = data_2.flatten()

    fig = go.Figure(go.Histogram2dContour(
        x=data_1,
        y=data_2,
    ))

    fig.update_layout(title="Correlation Density Plot [DEMO]")

    return fig
Exemplo n.º 2
0
def make_heat_map(df, player, lat_column, long_column, length=103, width=66):
    '''
    Creates heat map from coordinates
    
    :param df: DataFrame of tracking data with coordinates and player names
    :param player: String value indicating player
    :param lat_column: String value indicating latitude column
    :param long_column: String value indicating longitude column
    :param length: size length of soccer pitch
    :param width: size width of soccer pitch
    :return: heat map of player coordinates
    '''

    fig = viz.create_empty_field(len_field=103, wid_field=66)

    player_data = df.loc[df['Player'] == player]

    fill_df = pd.DataFrame(
        [[player, np.nan, 0, 0], [player, np.nan, 0, width],
         [player, np.nan, length, 0], [player, np.nan, length, width]],
        columns=player_data.columns)

    player_data = pd.concat([player_data, fill_df], ignore_index=True)

    #     px.density_contour(df, x = "Converted Latitude", y = "Converted Longitude")

    fig.add_trace(
        go.Histogram2dContour(x=player_data[lat_column],
                              y=player_data[long_column]))

    return fig
 def plot_std_scatter(self, x_axis_column_name, y_axis_column_name, scale):
     plot_df = filter_by_scale(scale, self.plot_df)
     x = np.log2(plot_df[x_axis_column_name] + 1)
     y = plot_df[y_axis_column_name]
     x_max = x.max()
     fig = go.Figure()
     x, y, density = get_density(x, y)
     fig.add_trace(
         go.Scattergl(x=x,
                      y=y,
                      mode='markers',
                      name='Value',
                      marker=dict(size=5,
                                  color=density,
                                  colorscale='viridis')))
     fig.add_trace(
         go.Histogram2dContour(x=x,
                               y=y,
                               name='Density',
                               contours={
                                   'coloring': 'none',
                                   'showlabels': True
                               }))
     fig.update_layout(showlegend=False,
                       autosize=False,
                       width=fig_size['square']['width'],
                       height=fig_size['square']['height'],
                       template=themes['large_single'])
     fig.update_xaxes(title_text='Log2(Estimated TPM+1)', range=[1, x_max])
     fig.update_yaxes(title_text='COV')
     return fig
Exemplo n.º 4
0
 def plot2d_rand(self):
     nbins = int(self.steps**0.5)
     fig = go.Figure()
     fig.add_trace(
         go.Histogram2dContour(x=self.random[0],
                               y=self.random[1],
                               xaxis='x',
                               yaxis='y',
                               line=dict(width=1),
                               contours=dict(coloring='none',
                                             showlabels=True,
                                             labelfont=dict(size=18)),
                               visible='legendonly',
                               name='Contour lines'))
     fig.add_trace(
         go.Scatter(x=self.random[0],
                    y=self.random[1],
                    xaxis='x',
                    yaxis='y',
                    mode='markers',
                    marker=dict(size=2),
                    name='X-Y distribution'))
     fig.add_trace(
         go.Histogram(x=self.random[0],
                      yaxis='y2',
                      name='X distribution',
                      nbinsx=nbins,
                      hovertemplate='value:%{x:.2f}' +
                      '<br>probability:%{y:.2f}<br>',
                      histnorm="probability"))
     fig.add_trace(
         go.Histogram(y=self.random[1],
                      xaxis='x2',
                      name='Y distribution',
                      nbinsy=nbins,
                      hovertemplate='value:%{y:.2f}' +
                      '<br>probability:%{x:.2f}<br>',
                      histnorm="probability"))
     fig.update_layout(template="plotly_white",
                       autosize=True,
                       xaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=True,
                                  range=self.axes_range[0]),
                       yaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=True,
                                  range=self.axes_range[1]),
                       xaxis2=dict(
                           zeroline=False,
                           domain=[0.9, 1],
                           showgrid=False,
                       ),
                       yaxis2=dict(zeroline=False,
                                   domain=[0.9, 1],
                                   showgrid=False),
                       legend=dict(font=dict(size=18),
                                   bgcolor="White",
                                   itemsizing='constant'))
     ply.plot(fig)
Exemplo n.º 5
0
 def plot_std_scatter(self, x_axis_column_names, y_axis_column_names,
                      scale):
     subplot_titles = [
         '{} {}'.format(M, [
             static_data.condition_1_name, static_data.condition_2_name
         ][i]) for i in range(2) for M in self.method_names
     ]
     fig = make_subplots(rows=2,
                         cols=len(self.method_names),
                         subplot_titles=subplot_titles,
                         vertical_spacing=0.2,
                         horizontal_spacing=0.05)
     col_num = 0
     row_num = 0
     x_maxs, y_maxs = [], []
     for x_axis_column_name, y_axis_column_name in zip(
             x_axis_column_names, y_axis_column_names):
         row_num += 1
         col_num = 0
         for plot_df, method_name, i in zip(self.plot_dfs,
                                            self.method_names,
                                            range(len(self.plot_dfs))):
             plot_df = filter_by_scale(scale, plot_df)
             col_num += 1
             x = plot_df[x_axis_column_name]
             y = plot_df[y_axis_column_name]
             x, y, density = get_density(x, y)
             fig.add_trace(go.Scattergl(x=x,
                                        y=y,
                                        mode='markers',
                                        name='Value',
                                        marker=dict(size=5,
                                                    color=density,
                                                    colorscale='viridis')),
                           row=row_num,
                           col=col_num)
             fig.add_trace(go.Histogram2dContour(x=x,
                                                 y=y,
                                                 name='Density',
                                                 contours={
                                                     'coloring': 'none',
                                                     'showlabels': True
                                                 }),
                           row=row_num,
                           col=col_num)
             fig.update_layout(showlegend=False)
             x_maxs.append(max(x))
             y_maxs.append(max(y))
     x_title = 'Log2(Estimated TPM+1)'
     y_title = 'COV'
     fig.update_xaxes(title_text=x_title, range=[1, max(x_maxs)])
     fig.update_yaxes(title_text=y_title, range=[0, max(y_maxs)])
     fig.update_layout(autosize=False,
                       width=fig_size['square']['width'] *
                       len(self.method_names),
                       height=fig_size['square']['height'] * 2,
                       template=themes['large_multi'])
     return fig
Exemplo n.º 6
0
 def plot_std_scatter(self, x_axis_column_names, y_axis_column_names,
                      scale):
     plot_df = filter_by_scale(scale, self.plot_df)
     subplot_titles = [
         static_data.condition_1_name, static_data.condition_2_name
     ]
     fig = make_subplots(rows=1,
                         cols=len(y_axis_column_names),
                         subplot_titles=subplot_titles)
     colorbars = [
         dict(len=1.05, x=0.45, y=0.49),
         dict(len=1.05, x=1.0, y=0.49)
     ]
     col_num = 0
     x_maxs, y_maxs = [], []
     for x_axis_column_name, y_axis_column_name, title in zip(
             x_axis_column_names, y_axis_column_names, subplot_titles):
         col_num += 1
         x = plot_df[x_axis_column_name]
         y = plot_df[y_axis_column_name]
         x, y, density = get_density(x, y)
         fig.add_trace(go.Scattergl(x=x,
                                    y=y,
                                    mode='markers',
                                    name=title,
                                    marker=dict(size=5,
                                                color=density,
                                                colorscale='viridis')),
                       row=1,
                       col=col_num)
         fig.add_trace(go.Histogram2dContour(x=x,
                                             y=y,
                                             name='Density_' + title,
                                             contours={
                                                 'coloring': 'none',
                                                 'showlabels': True
                                             }),
                       row=1,
                       col=col_num)
         x_maxs.append(max(x))
         y_maxs.append(max(y))
         out_df = pd.DataFrame({'Log2(true abundance+1)': x, 'std': y})
         out_df.to_csv(f'{static_data.output_dir}/std_scatter_{title}.tsv',
                       sep='\t')
     x_title = 'Log2(Estimated TPM+1)'
     y_title = 'Coefficient of variation'
     fig.update_xaxes(title_text=x_title, range=[1, max(x_maxs)])
     fig.update_yaxes(title_text=y_title, range=[0, max(y_maxs)])
     fig.update_layout(showlegend=False,
                       autosize=False,
                       width=fig_size['square']['width'] * 2,
                       height=fig_size['square']['height'],
                       template=themes['small_multi'])
     return fig
Exemplo n.º 7
0
def update_graph(option_selected,team_selected):
    
    print(option_selected)
    
    container = []
    
    layout = go.Layout(
        title=option_selected,
        
        hovermode='closest',
        shapes=rink_shapes(),
        yaxis=dict(
            range=[0, 100],
            scaleanchor="x",
            scaleratio=1,
            ticks='',
            showticklabels=True,
            zeroline=False,
            showgrid=False),
        xaxis=dict(
            range=[-50, 50],
            ticks='',
            showticklabels=True,
            zeroline=False,
            showgrid=False),
        height=700,
        width=700,
    )
    
    dff = data_Shots.copy()
    dff = dff[dff['Year'] == option_selected]
    
    if team_selected == 'All':
        pass
    else:
        dff = dff[dff['Team'] == team_selected]
    
    x = dff['X-Location']
    y = dff['Y-Location']
    
    data = [go.Histogram2dContour(x = y, y = x,
                              colorscale = [[0, 'rgb(255,255,255)'],[1, 'rgb(0,10,255)']],
                              opacity = 0.7,
                              reversescale=False,
                              ncontours=10,
                              histfunc = 'avg'
                              )]  
    
    
    
    fig = go.Figure(layout = layout, data=data)
    
    return container, fig
Exemplo n.º 8
0
def add_2d_hist(fig, x, y, row, col, legend=False):
    fig.add_trace(
        go.Histogram2dContour(
            x=x,
            y=y,
            reversescale=True,
            xaxis="x",
            yaxis="y",
            showlegend=legend,
        ),
        row=row,
        col=col,
    )
Exemplo n.º 9
0
 def plot_corr_scatter(self, x_axis_column_names, y_axis_column_names,
                       scale):
     plot_df = filter_by_scale(scale, self.plot_df)
     subplot_titles = [
         static_data.condition_1_name, static_data.condition_2_name
     ]
     fig = make_subplots(rows=1,
                         cols=len(y_axis_column_names),
                         subplot_titles=subplot_titles)
     # estimated_columns = [x for x in list(plot_df.columns) if 'estimated_abund_' in x]
     # true_columns = [x for x in list(plot_df.columns) if 'true_abund_' in x]
     x_maxs, y_maxs = [], []
     col_num = 0
     for x_axis_column_name, y_axis_column_name in zip(
             x_axis_column_names, y_axis_column_names):
         col_num += 1
         df = plot_df[(plot_df[x_axis_column_name] >= 1)
                      & (plot_df[y_axis_column_name] >= 1)]
         x, y, density = get_density(df[x_axis_column_name],
                                     df[y_axis_column_name])
         fig.add_trace(go.Scatter(x=x,
                                  y=y,
                                  mode='markers',
                                  name='Value',
                                  marker=dict(size=5,
                                              color=density,
                                              colorscale='viridis')),
                       row=1,
                       col=col_num)
         fig.add_trace(go.Histogram2dContour(x=x,
                                             y=y,
                                             name='Density',
                                             contours={
                                                 'coloring': 'none',
                                                 'showlabels': True
                                             }),
                       row=1,
                       col=col_num)
         x_maxs.append(x.max())
         y_maxs.append(y.max())
     x_title = 'Log2(True TPM+1)'
     y_title = 'Log2(Estimated TPM+1)'
     fig.update_xaxes(title_text=x_title, range=[1, max(x_maxs + y_maxs)])
     fig.update_yaxes(title_text=y_title, range=[1, max(x_maxs + y_maxs)])
     fig.update_layout(showlegend=False,
                       autosize=False,
                       width=fig_size['square']['width'] * 2,
                       height=fig_size['square']['height'],
                       template=themes['large_single'])
     return fig
Exemplo n.º 10
0
def plot_distribution(random_sample, bins):
    fig = go.Figure(data=[go.Histogram(x=random_sample, nbinsx=bins)])
    fig.update_layout(title_text="Гистограмма")
    st.write(fig)

    fig = ff.create_distplot([random_sample], [""],
                             bin_size=.2,
                             show_hist=False)
    fig.update_layout(title_text="Плотность")
    st.write(fig)

    fig = go.Figure(go.Histogram2dContour(x=random_sample, y=random_sample))
    fig.update_layout(title_text="Контуры плотности")
    st.write(fig)
Exemplo n.º 11
0
def grades_pace_contour(streams, stats):
    '''
    Create Figrue
    '''
    fig = go.Figure()

    fig.add_trace(
        go.Histogram2dContour(y=streams['gap'],
                              x=streams['grade'],
                              ybins=dict(start=0),
                              histnorm='percent',
                              colorscale='Blues'))

    return fig
Exemplo n.º 12
0
 def plot_corr_scatter(self, x_axis_column_name, y_axis_column_name, scale):
     fig = make_subplots(rows=1,
                         cols=len(self.plot_dfs),
                         vertical_spacing=0.2,
                         horizontal_spacing=0.1,
                         subplot_titles=self.method_names)
     x_maxs, y_maxs = [], []
     for plot_df, method_name, i in zip(self.plot_dfs, self.method_names,
                                        range(len(self.plot_dfs))):
         plot_df = filter_by_scale(scale, plot_df)
         plot_df = plot_df[(np.log2(plot_df[x_axis_column_name] + 1) >= 1) &
                           (np.log2(plot_df[y_axis_column_name] + 1) >= 1)]
         x = plot_df[x_axis_column_name]
         y = plot_df[y_axis_column_name]
         x = np.log2(x + 1)
         y = np.log2(y + 1)
         x_maxs.append(x.max())
         y_maxs.append(y.max())
         x, y, density = get_density(x, y)
         fig.add_trace(go.Scattergl(x=x,
                                    y=y,
                                    mode='markers',
                                    name='Value',
                                    marker=dict(size=5,
                                                color=density,
                                                colorscale='viridis'),
                                    showlegend=False),
                       col=i + 1,
                       row=1)
         fig.add_trace(go.Histogram2dContour(x=x,
                                             y=y,
                                             name='Density',
                                             contours={
                                                 'coloring': 'none',
                                                 'showlabels': True
                                             },
                                             showlegend=False),
                       col=i + 1,
                       row=1)
     x_title = 'Log2(True TPM+1)'
     y_title = 'Log2(Estimated TPM+1)'
     fig.update_layout(autosize=False,
                       width=fig_size['square']['width'] *
                       len(self.plot_dfs),
                       height=fig_size['square']['height'],
                       template=themes['medium_multi'])
     fig.update_xaxes(title_text=x_title, range=[1, max(x_maxs + y_maxs)])
     fig.update_yaxes(title_text=y_title, range=[1, max(x_maxs + y_maxs)])
     return fig
Exemplo n.º 13
0
def make_heatmap(fig, shots_df, name, season_id):
    cubehelix_cs=[[0.0, '#ffffff'],[0.16666666666666666, '#edcfc9'],[0.3333333333333333, '#daa2ac'],[0.5, '#bc7897'],
    [0.6666666666666666, '#925684'],[0.8333333333333333, '#5f3868'],[1.0, '#2d1e3e']]

    fig.add_trace(go.Histogram2dContour(
        x = shots_df['LOC_X'],
        y = shots_df['LOC_Y'],
        colorscale=cubehelix_cs,
        contours=dict(showlines=False)))

    fig.update_layout(
        title={
            'text': f"{name} {season_id} Shot Heatmap",
            'y':0.98,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top'})
def age_totalworkingyears_distplot():
    df = dataset()
    x = df.Age
    y = df.TotalWorkingYears

    fig = go.Figure()
    fig.add_trace(
        go.Histogram2dContour(x=x,
                              y=y,
                              colorscale='Blues',
                              reversescale=True,
                              xaxis='x',
                              yaxis='y'))
    fig.add_trace(
        go.Scatter(x=x,
                   y=y,
                   xaxis='x',
                   yaxis='y',
                   mode='markers',
                   marker=dict(color='rgba(0,0,0,0.3)', size=3)))
    fig.add_trace(
        go.Histogram(y=y, xaxis='x2', marker=dict(color='rgba(0,0,0,1)')))
    fig.add_trace(
        go.Histogram(x=x, yaxis='y2', marker=dict(color='rgba(0,0,0,1)')))

    fig.update_layout(autosize=False,
                      xaxis=dict(zeroline=False,
                                 domain=[0, 0.85],
                                 showgrid=False),
                      yaxis=dict(zeroline=False,
                                 domain=[0, 0.85],
                                 showgrid=False),
                      xaxis2=dict(zeroline=False,
                                  domain=[0.85, 1],
                                  showgrid=False),
                      yaxis2=dict(zeroline=False,
                                  domain=[0.85, 1],
                                  showgrid=False),
                      height=600,
                      width=600,
                      bargap=0,
                      hovermode='closest',
                      showlegend=False)
    return fig_json(fig)
Exemplo n.º 15
0
def visualize_search_performance_heatmap(hopt_exp_results):

    identifiers = hopt_exp_results.columns.levels[0]

    fig = make_subplots(rows=1,
                        cols=len(identifiers),
                        subplot_titles=identifiers)

    for j, identifier in enumerate(identifiers):
        data = hopt_exp_results[identifier]
        x = list(data.columns.values) * len(data.index)
        y = data.values.flatten()
        fig.add_trace(go.Histogram2dContour(x=x, y=y, name=identifier),
                      row=1,
                      col=j + 1)

    fig.update_yaxes(title_text="Mean squared error")
    fig.update_xaxes(title_text="Iterations")

    fig.show()
def update_data_graph(value_x, value_y, value_color, data_feature,
                      data_target):
    df_feature = pd.DataFrame(data_feature, dtype='float')
    df_target = pd.DataFrame(data_target, dtype='float')
    df = pd.concat([df_feature, df_target], axis=1)
    if ((value_x != None) and (value_y != None) and (value_color != None)):
        fig = px.scatter(df,
                         x=value_x,
                         y=value_y,
                         color=value_color,
                         color_continuous_scale=px.colors.diverging.RdYlGn_r,
                         height=600)
        graph1 = dcc.Graph(figure=fig)

        fig = go.Figure(
            go.Histogram2dContour(x=df[value_x],
                                  y=df[value_y],
                                  z=df[value_color],
                                  histfunc='avg',
                                  colorscale='hot_r',
                                  contours=dict(
                                      start=0,
                                      end=df[value_color].max() * 1.1,
                                      size=df[value_color].max() / 10,
                                      showlabels=True,
                                      labelfont=dict(family='Raleway',
                                                     color='blue',
                                                     size=22)),
                                  hoverlabel=dict(bgcolor='white',
                                                  bordercolor='black',
                                                  font=dict(family='Raleway',
                                                            color='black'))))
        fig.update_layout(xaxis_title_text=value_x,
                          yaxis_title_text=value_y,
                          height=600)
        graph2 = dcc.Graph(figure=fig)

        return [[graph1, graph2]]
    else:
        raise PreventUpdate
Exemplo n.º 17
0
def render_map(data):
    # Create figure
    fig = make_subplots(rows=2,
                        cols=1,
                        row_heights=[0.1, 0.9],
                        vertical_spacing=0.09)

    data_cols = data.columns[3:]
    dates = data["date"].unique()
    filtered_data = data[data["date"] == dates[0]]

    # Add timeseries
    ts = pd.read_csv("a3_data/dates.csv")

    fig.add_trace(go.Scatter(type="scatter",
                             mode="lines",
                             name='Disease Posts Per Day',
                             x=ts["Date"],
                             y=ts["0"],
                             line={"color": '#17BECF'}),
                  row=1,
                  col=1)

    # Load weather data
    weather = pd.read_csv("./a3_data/Weather.csv")

    # Add heatmap
    fig.add_trace(
        # go.Scatter(
        #     x=filtered_data["x"], y=filtered_data["y"],
        #     mode='markers', hoverinfo="text",
        #     hovertext=filtered_data[data_cols[0]],
        #     marker_size=filtered_data[data_cols[0]],
        # )
        go.Histogram2dContour(
            x=filtered_data["x"],
            y=filtered_data["y"],
            z=filtered_data[data_cols[0]],
            # hovertemplate="%{z}",
            hoverinfo="z",
            opacity=0.7,
            colorscale='Jet',
            histfunc='sum',
            xbins=dict(size=32),
            ybins=dict(size=32),
            line=dict(width=0)),
        row=2,
        col=1,
    )

    # Add opacity slider
    steps = []
    for i in [i / 10. for i in range(0, 11, 1)]:
        step = dict(
            args=[dict(opacity=[[], i])],
            method="restyle",
            label="{:.1f}".format(i),
        )
        steps.append(step)

    sliders = [
        dict(active=7,
             currentvalue={"prefix": "Opacity: "},
             pad={"t": 50},
             steps=steps)
    ]

    # Add images
    img = Image.open('./a3_data/Vastopolis_Map.png')
    fig.add_layout_image(dict(
        source=img,
        xref="x",
        yref="y",
        x=0,
        y=YMAX,
        sizex=XMAX,
        sizey=YMAX,
        sizing="stretch",
        opacity=1,
        layer="below",
    ),
                         row=2,
                         col=1)

    menu, annotations = make_menu(data_cols, dates, data, ts, weather)

    # Set templates
    fig.update_layout(template="plotly_white")
    fig.update_xaxes(showgrid=False,
                     range=[0, XMAX],
                     showticklabels=False,
                     row=2,
                     col=1)
    fig.update_yaxes(showgrid=False,
                     range=[0, YMAX],
                     showticklabels=False,
                     row=2,
                     col=1)
    fig.update_layout(updatemenus=menu,
                      sliders=sliders,
                      annotations=annotations)

    fig.write_html("index.html")
    fig.show()
Exemplo n.º 18
0
def nhanes_multivariate_analysis(df):
    st.write(""" 
  ### Quantitative bivariate data

  Bivariate data arise when every "unit of analysis" (e.g. a person in the NHANES dataset) is assessed with respect to two traits (the NHANES subjects were assessed for many more than two traits, but we can consider two traits at a time here).
  
  Below we make a scatterplot of arm length against leg length.  This means that arm length ([BMXARML](https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/BMX_I.htm#BMXARML)) is plotted on the vertical axis and leg length ([BMXLEG](https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/BMX_I.htm#BMXLEG)) is plotted on the horizontal axis).  We see a positive dependence between the two measures -- people with longer arms tend to have longer legs, and vice-versa.  However it is far from a perfect relationship.
  """)

    df["RIAGENDRx"] = df.RIAGENDR.replace({1: "Male", 2: "Female"})
    fig = px.scatter(df,
                     x="BMXLEG",
                     y="BMXARML",
                     color="RIAGENDRx",
                     opacity=0.5,
                     title="Correlation arm length against leg length")
    st.plotly_chart(fig)

    st.write(""" 
  This plot also shows the Pearson correlation coefficient between the arm length and leg length, which is 0.62. The Pearson correlation coefficient ranges from -1 to 1, with values approaching 1 indicating a more perfect positive dependence.  In many settings, a correlation of 0.62 would be considered a moderately strong positive dependence. 
  """)

    fig = px.density_contour(
        df,
        x="BMXLEG",
        y="BMXARML",
        title="Contour correlation between arm length and leg length")
    fig.add_annotation(x=50,
                       y=45,
                       text="p=0.62",
                       font=dict(color="white", size=12),
                       showarrow=False)
    fig.update_traces(contours_coloring="fill", contours_showlabels=True)
    st.plotly_chart(fig)

    st.write(""" 
  As another example with slightly different behavior, we see that systolic and diastolic blood pressure (essentially the maximum and minimum blood pressure between two consecutive heart beats) are more weakly correlated than arm and leg length, with a correlation coefficient of 0.32. This weaker correlation indicates that some people have unusually high systolic blood pressure but have average diastolic blood pressure, and vice versa.
  """)
    fig = px.density_contour(df,
                             x="BPXSY1",
                             y="BPXDI1",
                             marginal_x="rug",
                             marginal_y="rug",
                             title="BPXSY1 and BPXDI1 correlation")
    fig.add_annotation(x=200,
                       y=100,
                       text="p=0.32",
                       font=dict(size=15, color="black"),
                       showarrow=False)
    st.plotly_chart(fig)

    st.write("""
  Next we look at two repeated measures of systolic blood pressure, taken a few minutes apart on the same person. These values are very highly correlated, with a correlation coefficient of around 0.96.
  """)
    x = df["BPXSY1"].to_numpy()
    y = df["BPXSY2"].to_numpy()
    fig = go.Figure(
        go.Histogram2dContour(x=x,
                              y=y,
                              colorscale='Jet',
                              contours=dict(showlabels=True,
                                            labelfont=dict(family='Raleway',
                                                           color='white')),
                              hoverlabel=dict(bgcolor='white',
                                              bordercolor='black',
                                              font=dict(family='Raleway',
                                                        color='black'))))

    fig.update_layout(title_text="BPXSY1 and BPXSY2 correlation", )
    fig.add_annotation(x=200,
                       y=200,
                       text="p=0.96",
                       font=dict(size=15, color="white"),
                       showarrow=False)
    st.plotly_chart(fig)

    st.write(""" 
  ### Heterogeneity and stratification

  Most human characteristics are complex -- they vary by gender, age, ethnicity, and other factors.  This type of variation is often referred to as "heterogeneity".  When such heterogeneity is present, it is usually productive to explore the data more deeply by stratifying on relevant factors, as we did in the univariate analyses.  

  Below, we continue to probe the relationship between leg length and arm length, stratifying first by gender, then by gender and ethnicity. The gender-stratified plot indicates that men tend to have somewhat longer arms and legs than women -- this is reflected in the fact that the cloud of points on the left is shifted slightly up and to the right relative to the cloud of points on the right.  In addition, the correlation between arm length and leg length appears to be somewhat weaker in women than in men.
  """)

    fig_fem = px.scatter(df, x="BMXLEG", y="BMXARML", facet_row="RIAGENDRx")
    st.plotly_chart(fig_fem, use_container_width=True)

    st.write(""" 
  Next we look to stratifying the data by both gender and ethnicity.  This results in 2 x 5 = 10 total strata, since there are 2 gender strata and 5 ethnicity strata. These scatterplots reveal differences in the means as well a diffrences in the degree of association (correlation) between different pairs of variables.  We see that although some ethnic groups tend to have longer/shorter arms and legs than others, the relationship between arm length and leg length within genders is roughly similar across the ethnic groups.  

  One notable observation is that ethnic group 5, which consists of people who report being multi-racial or are of any race not treated as a separate group (due to small sample size), the correlation between arm length and leg length is stronger, especially for men.  This is not surprising, as greater heterogeneity can allow correlations to emerge that are indiscernible in more homogeneous data.   
  """)

    fig = px.density_contour(df,
                             x="BMXLEG",
                             y="BMXARML",
                             facet_col="RIDRETH1",
                             facet_row="RIAGENDRx")
    fig.update_traces(contours_coloring="fill", contours_showlabels=True)
    st.plotly_chart(fig)
Exemplo n.º 19
0
import plotly as py
import pandas as pd

x0 = pd.read_csv('highstatdocas.csv')

fig = go.Figure()

data = [
    go.Histogram2dContour(
        x=x0['recodoca'],
        y=x0['truedoca'],
        xbins=dict(start=0, end=2.5, size=0.025),
        ybins=dict(start=0, end=2.5, size=0.025),
        colorscale='YlGnBu',
        zmax=10,
        nbinsx=14,
        nbinsy=14,
        zauto=False,
        #colorscale = 'Jet',
        contours=dict(showlabels=True,
                      labelfont=dict(family='Raleway', color='black')),
        hoverlabel=dict(bgcolor='white',
                        bordercolor='white',
                        font=dict(family='Raleway', color='black'))),
    go.Histogram(y=x0['truedoca'],
                 xaxis='x2',
                 marker=dict(color='rgba(0,0,0,1)')),
    go.Histogram(x=x0['recodoca'],
                 yaxis='y2',
                 marker=dict(color='rgba(0,0,0,1)'))
]
Exemplo n.º 20
0
import plotly as py

x0 = pd.read_csv('highstatdocas.csv')

fig = go.Figure()

data = [
    go.Histogram2dContour(
        x=x0['FitA0'],
        y=x0['TrueA0'],
        xbins=dict(start=-6000, end=6000, size=50),
        ybins=dict(start=-6000, end=6000, size=50),
        colorscale='YlGnBu',
        zmax=10,
        nbinsx=14,
        nbinsy=14,
        zauto=False,
        #colorscale = 'Jet',
        contours=dict(showlabels=True,
                      labelfont=dict(family='Raleway', color='black')),
        hoverlabel=dict(bgcolor='white',
                        bordercolor='white',
                        font=dict(family='Raleway', color='black'))),
    go.Histogram(y=x0['TrueA0'],
                 xaxis='x2',
                 xbins=dict(start=-6000, end=6000, size=50),
                 marker=dict(color='rgba(0,0,0,1)')),
    go.Histogram(x=x0['FitA0'],
                 yaxis='y2',
                 ybins=dict(start=-6000, end=6000, size=50),
                 marker=dict(color='rgba(0,0,0,1)'))
Exemplo n.º 21
0
def PairwiseDensityPlot(df,
                        X=None,
                        Y=None,
                        scatter=True,
                        width=800,
                        height=800):

    if not X:
        X = df.select_dtypes(
            include=['bool', 'float', 'int', 'category']).columns.values

    if not Y:
        Y = df.select_dtypes(
            include=['bool', 'float', 'int', 'category']).columns.values

    assert Basic.isCollection(
        X
    ), "X needs to be a collection type. If inputting only a single value, add it as a list."
    assert Basic.isCollection(
        Y
    ), "Y needs to be a collection type. If inputting only a single value, add it as a list."

    x = df[X[0]].values
    y = df[Y[0]].values

    x_dropdown = widgets.Dropdown(
        options=X,
        value=X[0],
        description='X Axis Value:',
    )

    y_dropdown = widgets.Dropdown(
        options=Y,
        value=Y[0],
        description='Y Axis Value:',
    )

    container = widgets.HBox([x_dropdown, y_dropdown])

    #start of figure
    traces = []

    traces.append(
        go.Histogram2dContour(x=x,
                              y=y,
                              colorscale='Blues',
                              reversescale=True,
                              xaxis='x',
                              yaxis='y',
                              name='Contour',
                              showscale=False))

    if scatter:
        #with enough datapoints, this will slow down the graph build or make it look fugly.
        traces.append(
            go.Scatter(x=x,
                       y=y,
                       xaxis='x',
                       yaxis='y',
                       mode='markers',
                       marker=dict(color='rgba(0,0,0,0.2)', size=2),
                       name='Data',
                       hoverinfo='skip'))

    traces.append(
        go.Histogram(y=y,
                     xaxis='x2',
                     marker=dict(color='rgba(0,0,0,1)'),
                     name='Histogram',
                     orientation='h'))
    traces.append(
        go.Histogram(x=x,
                     yaxis='y2',
                     marker=dict(color='rgba(0,0,0,1)'),
                     name='Histogram'))
    layout = go.Layout(autosize=True,
                       width=width,
                       height=height,
                       xaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       yaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       xaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       yaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       bargap=0,
                       showlegend=False,
                       margin=dict(l=10, r=10, t=10, b=10))

    g = go.FigureWidget(data=traces, layout=layout)

    def response(change):
        x = df[x_dropdown.value].values
        y = df[y_dropdown.value].values

        update_range = 4 if scatter else 3
        yhist = 1 if scatter else 2

        with g.batch_update():
            for i in range(0, update_range):
                g.data[i].x = x
                g.data[i].y = y
                g.layout.xaxis.title = x_dropdown.value
                g.layout.yaxis.title = y_dropdown.value

    x_dropdown.observe(response, names="value")
    y_dropdown.observe(response, names="value")

    Title(
        title="Interactive Density Plot",
        description="Select values for X and Y axis to view varying densities."
    )
    display(widgets.VBox([container, g]))

    return
Exemplo n.º 22
0
import plotly
import plotly.graph_objects as go
# import plotly.plotly as py
import plotly.graph_objs as go
#from plotly.widgets import GraphWidget
from IPython.display import display, clear_output, Image
# The old way to use plotly in Jupyter is to use iplot
# either online (if you have an account) or offline
from plotly.offline import iplot


    
x = np.random.randn(8)
y = np.random.randn(8)
# iplot([go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
fig = go.FigureWidget(data=go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')))
fig.update_layout(
                autosize=True,
                width= 600,
                height=600,
)

islide = IntSlider()

def redo_plot(b):
    print(islide.value)
    
islide.observe(redo_plot)

VBox([islide,fig])
Exemplo n.º 23
0
    def __init__(self):

        self.output_dir = '.'
        # self.output_dir = 'tmpdir'

        self.figsize_width_substrate = 15.0  # allow extra for colormap
        self.figsize_height_substrate = 12.5
        self.figsize_width_svg = 12.0
        self.figsize_height_svg = 12.0

        # self.fig = plt.figure(figsize=(self.figsize_width_substrate, self.figsize_height_substrate))
        # self.fig = plt.figure()
        self.fig = None

        # self.fig = plt.figure(figsize=(7.2,6))  # this strange figsize results in a ~square contour plot

        self.first_time = True
        self.modulo = 1

        self.use_defaults = True

        self.svg_delta_t = 1
        self.substrate_delta_t = 1
        self.svg_frame = 1
        self.substrate_frame = 1

        self.customized_output_freq = False
        self.therapy_activation_time = 1000000
        self.max_svg_frame_pre_therapy = 1000000
        self.max_substrate_frame_pre_therapy = 1000000

        self.svg_xmin = 0

        # Probably don't want to hardwire these if we allow changing the domain size
        # self.svg_xrange = 2000
        # self.xmin = -1000.
        # self.xmax = 1000.
        # self.ymin = -1000.
        # self.ymax = 1000.
        # self.x_range = 2000.
        # self.y_range = 2000.

        self.show_nucleus = False
        self.show_edge = True

        # initial value
        self.field_index = 4
        # self.field_index = self.mcds_field.value + 4

        # define dummy size of mesh (set in the tool's primary module)
        self.numx = 0
        self.numy = 0

        self.title_str = ''

        tab_height = '600px'
        tab_height = '500px'
        constWidth = '180px'
        constWidth2 = '150px'
        tab_layout = Layout(
            width='900px',  # border='2px solid black',
            height=tab_height,
        )  #overflow_y='scroll')

        max_frames = 2
        # self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)
        # self.i_plot = interactive(self.plot_plots, frame=(0, max_frames), continuous_update=False)

        # self.i_plot = interactive(self.plot_substrate0, frame=(0, max_frames), continuous_update=False)
        self.i_plot = interactive(self.plot_substrate,
                                  frame=(0, max_frames),
                                  continuous_update=False)

        self.frame_slider = IntSlider(
            min=0,
            max=10,
            step=1,
            description='Test:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
        )
        # self.frame_slider.observe(self.frame_slider_cb)
        self.frame_slider.observe(self.plot_substrate)

        # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that)
        # NOTE: the Substrates Plot tab has an extra row of widgets at the top of it (cf. Cell Plots tab)
        svg_plot_size = '700px'
        svg_plot_size = '600px'
        svg_plot_size = '700px'
        svg_plot_size = '900px'
        self.i_plot.layout.width = svg_plot_size
        self.i_plot.layout.height = svg_plot_size

        self.fontsize = 20

        # description='# cell frames',
        self.max_frames = BoundedIntText(
            min=0,
            max=99999,
            value=max_frames,
            description='# frames',
            layout=Layout(width='160px'),
        )
        self.max_frames.observe(self.update_max_frames)

        # self.field_min_max = {'dummy': [0., 1.]}
        # NOTE: manually setting these for now (vs. parsing them out of data/initial.xml)
        self.field_min_max = {
            'director signal': [0., 1.],
            'cargo signal': [0., 1.]
        }
        # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below
        # self.field_dict = {0:'dummy'}
        self.field_dict = {0: 'director signal', 1: 'cargo signal'}

        self.mcds_field = Dropdown(
            options={
                'director signal': 0,
                'cargo signal': 1
            },
            value=0,
            #     description='Field',
            layout=Layout(width=constWidth))
        # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value)
        #        self.mcds_field.observe(self.mcds_field_cb)
        self.mcds_field.observe(self.mcds_field_changed_cb)

        # self.field_cmap = Text(
        #     value='viridis',
        #     description='Colormap',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        self.field_cmap = Dropdown(
            options=['viridis', 'jet', 'YlOrRd'],
            value='YlOrRd',
            #     description='Field',
            layout=Layout(width=constWidth))
        #        self.field_cmap.observe(self.plot_substrate)
        self.field_cmap.observe(self.mcds_field_cb)

        self.cmap_fixed = Checkbox(
            description='Fix',
            disabled=False,
            #           layout=Layout(width=constWidth2),
        )

        self.save_min_max = Button(
            description='Save',  #style={'description_width': 'initial'},
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Save min/max for this substrate',
            disabled=True,
            layout=Layout(width='90px'))

        def save_min_max_cb(b):
            #            field_name = self.mcds_field.options[]
            #            field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value)
            field_name = self.field_dict[self.mcds_field.value]
            #            print(field_name)
            #            self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]}
            self.field_min_max[field_name][0] = self.cmap_min.value
            self.field_min_max[field_name][1] = self.cmap_max.value
#            print(self.field_min_max)

        self.save_min_max.on_click(save_min_max_cb)

        self.cmap_min = FloatText(
            description='Min',
            value=0,
            step=0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_min.observe(self.mcds_field_cb)

        self.cmap_max = FloatText(
            description='Max',
            value=38,
            step=0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_max.observe(self.mcds_field_cb)

        def cmap_fixed_cb(b):
            if (self.cmap_fixed.value):
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.save_min_max.disabled = False
            else:
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.save_min_max.disabled = True
#            self.mcds_field_cb()

        self.cmap_fixed.observe(cmap_fixed_cb)

        field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed])

        #        field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max])
        items_auto = [
            self.save_min_max,  #layout=Layout(flex='3 1 auto', width='auto'),
            self.cmap_min,
            self.cmap_max,
        ]
        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='80%')
        field_cmap_row3 = Box(children=items_auto, layout=box_layout)

        #---------------------
        self.cell_nucleus_toggle = Checkbox(
            description='nuclei',
            disabled=False,
            value=self.show_nucleus,
            #           layout=Layout(width=constWidth2),
        )

        def cell_nucleus_toggle_cb(b):
            # self.update()
            if (self.cell_nucleus_toggle.value):
                self.show_nucleus = True
            else:
                self.show_nucleus = False
            self.i_plot.update()

        self.cell_nucleus_toggle.observe(cell_nucleus_toggle_cb)

        #----
        self.cell_edges_toggle = Checkbox(
            description='edges',
            disabled=False,
            value=self.show_edge,
            #           layout=Layout(width=constWidth2),
        )

        def cell_edges_toggle_cb(b):
            # self.update()
            if (self.cell_edges_toggle.value):
                self.show_edge = True
            else:
                self.show_edge = False
            self.i_plot.update()

        self.cell_edges_toggle.observe(cell_edges_toggle_cb)

        self.cells_toggle = Checkbox(
            description='Cells',
            disabled=False,
            value=True,
            #           layout=Layout(width=constWidth2),
        )

        def cells_toggle_cb(b):
            # self.update()
            self.i_plot.update()
            if (self.cells_toggle.value):
                self.cell_edges_toggle.disabled = False
                self.cell_nucleus_toggle.disabled = False
            else:
                self.cell_edges_toggle.disabled = True
                self.cell_nucleus_toggle.disabled = True

        self.cells_toggle.observe(cells_toggle_cb)

        #---------------------
        self.substrates_toggle = Checkbox(
            description='Substrates',
            disabled=False,
            value=True,
            #           layout=Layout(width=constWidth2),
        )

        def substrates_toggle_cb(b):
            if (self.substrates_toggle.value):  # seems bass-ackwards
                self.cmap_fixed.disabled = False
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.mcds_field.disabled = False
                self.field_cmap.disabled = False
            else:
                self.cmap_fixed.disabled = True
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.mcds_field.disabled = True
                self.field_cmap.disabled = True

        self.substrates_toggle.observe(substrates_toggle_cb)

        self.grid_toggle = Checkbox(
            description='grid',
            disabled=False,
            value=True,
            #           layout=Layout(width=constWidth2),
        )

        def grid_toggle_cb(b):
            # self.update()
            self.i_plot.update()

        self.grid_toggle.observe(grid_toggle_cb)

        #        field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max])

        # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout)
        # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames])  # mcds_dir
        #        mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,])  # mcds_dir

        #        self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout)

        help_label = Label('select slider: drag or left/right arrows')
        # row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black',
        row1a = Box([self.max_frames, self.mcds_field, self.field_cmap],
                    layout=Layout(border='1px solid black',
                                  width='50%',
                                  height='',
                                  align_items='stretch',
                                  flex_direction='row',
                                  display='flex'))
        row1b = Box([
            self.cells_toggle, self.cell_nucleus_toggle, self.cell_edges_toggle
        ],
                    layout=Layout(border='1px solid black',
                                  width='50%',
                                  height='',
                                  align_items='stretch',
                                  flex_direction='row',
                                  display='flex'))
        row1 = HBox([row1a, Label('.....'), row1b])

        row2a = Box([self.cmap_fixed, self.cmap_min, self.cmap_max],
                    layout=Layout(border='1px solid black',
                                  width='50%',
                                  height='',
                                  align_items='stretch',
                                  flex_direction='row',
                                  display='flex'))
        # row2b = Box( [self.substrates_toggle, self.grid_toggle], layout=Layout(border='1px solid black',
        row2b = Box([
            self.substrates_toggle,
        ],
                    layout=Layout(border='1px solid black',
                                  width='50%',
                                  height='',
                                  align_items='stretch',
                                  flex_direction='row',
                                  display='flex'))
        # row2 = HBox( [row2a, self.substrates_toggle, self.grid_toggle])
        row2 = HBox([row2a, Label('.....'), row2b])

        row3 = HBox([
            self.frame_slider,
        ])

        if (hublib_flag):
            self.download_button = Download('mcds.zip',
                                            style='warning',
                                            icon='cloud-download',
                                            tooltip='Download data',
                                            cb=self.download_cb)

            self.download_svg_button = Download(
                'svg.zip',
                style='warning',
                icon='cloud-download',
                tooltip='You need to allow pop-ups in your browser',
                cb=self.download_svg_cb)
            download_row = HBox([
                self.download_button.w, self.download_svg_button.w,
                Label("Download all cell plots (browser must allow pop-ups).")
            ])

            # box_layout = Layout(border='0px solid')
            # controls_box = VBox([row1, row2])  # ,width='50%', layout=box_layout)
            controls_box = VBox([row1, row2,
                                 row3])  # ,width='50%', layout=box_layout)

            # self.tab = VBox([controls_box, self.i_plot, download_row])

            #            graph = GraphWidget()
            # iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])
            # self.fig = go.FigureWidget(data=go.Bar(y=[2, 3, 1]))

            # x = np.random.randn(2000)
            # y = np.random.randn(2000)
            self.x = np.random.randn(2)
            self.y = np.random.randn(2)
            # iplot([go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
            # self.fig = go.FigureWidget(data=go.Histogram2dContour(x=x, y=y, contours_showlines=False, contours=dict(coloring='heatmap')))
            self.fig = go.FigureWidget(data=go.Histogram2dContour(
                x=self.x, y=self.y, contours=dict(coloring='heatmap')))

            # self.fig = go.FigureWidget( data = [
            #     {
            #     'type' : 'Histogram2dContour',
            #     'x' : self.x,
            #     'y' : self.y,
            #     'contours' : {
            #         'coloring': 'heatmap'
            #     }
            #     },
            #     {
            #     'type' : 'scatter',
            #     'x' : self.x,
            #     'y' : self.y,
            #     'line' : {
            #         'color': 'red',
            #         'width': 3
            #     }
            #     }
            #     ], layout={})
            # self.fig = go.FigureWidget(data=go.Contour(x=x, y=y, contours=dict(coloring='heatmap')))

            # x = np.linspace(-10, 10, 400)
            # y = np.linspace(-5, 5, 400)
            # x, y = np.meshgrid(x, y)
            # a = 1
            # b = 2
            # z = x**2/a**2 - y**2/b**2
            # contour = go.Contour(
            #     z=z
            # )
            # contour.contours.type = 'constraint'
            # contour.contours.value = 8
            # data = [contour]
            # # self.fig = go.Figure(data=data)
            # self.fig = go.FigureWidget(data=data)

            #                go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3, opacity=0.3)), show_link=False)
            self.fig.update_layout(  # square figure layout for plotly?
                autosize=True,
                margin=dict(l=20, r=20, t=30, b=20),
                width=800,
                height=800,
                # margin=dict(
                #     l=50,
                #     r=50,
                #     b=100,
                #     t=100,
                #     pad=4
                # ),
                # paper_bgcolor="White",
                # paper_bgcolor="LightSteelBlue",
            )

            self.tab = VBox([controls_box, self.fig,
                             download_row])  # plotly approach

            # app_layout = AppLayout(
            #     center= self.fig.canvas,
            #     # footer= self.frame_slider,
            #     pane_heights=[0, 6, 1]
            # )
            # self.tab = app_layout

            # self.tab = VBox([controls_box, self.fig.canvas, download_row])

#        self.fig = plt.figure(figsize=(self.figsize_width_substrate, self.figsize_height_substrate))

        else:
            # self.tab = VBox([row1, row2])
            self.tab = VBox([row1, row2, self.i_plot])
Exemplo n.º 24
0
def plot_comparison_both_probabilities(
            vocab,
            model_name="model",
            show_plot=True,
            save_plot=True,
            save_folder="data"):

    x = vocab["german_proba"]
    y = vocab["english_proba"]
    text = vocab["german"] + " - " + vocab["english"]

    fig = go.Figure()
    fig.add_trace(
        go.Histogram2dContour(
            x=x, y=y, colorscale="Blues", reversescale=True, xaxis="x", yaxis="y"
        )
    )
    fig.add_trace(
        go.Scatter(
            x=x,
            y=y,
            xaxis="x",
            yaxis="y",
            mode="markers",
            marker=dict(color="rgba(0,0,0,0.3)", size=3),
            text=text,
        )
    )

    fig.add_trace(
        go.Scatter(
            x=[0.9, 0.9],
            y=[0, 1],
            xaxis="x",
            yaxis="y",
            showlegend=False,
            mode="lines",
            line=dict(color="white", width=0.2, dash="dash"),
        )
    )

    fig.add_trace(
        go.Scatter(
            x=[0, 1],
            y=[0.9, 0.9],
            xaxis="x",
            yaxis="y",
            showlegend=False,
            mode="lines",
            line=dict(color="white", width=0.2, dash="dash"),
        )
    )

    fig.add_trace(
        go.Histogram(
            y=y, xaxis="x2", marker=dict(color="rgba(0,0,0,1)"), ybins=dict(size=0.05)
        )
    )
    fig.add_trace(
        go.Histogram(
            x=x, yaxis="y2", marker=dict(color="rgba(0,0,0,1)"), xbins=dict(size=0.05)
        )
    )

    fig.update_layout(
        title="Distributions of the probabilities",
        xaxis_title="German probability",
        yaxis_title="English probability",
        autosize=False,
        xaxis=dict(zeroline=False, domain=[0, 0.85], showgrid=False),
        yaxis=dict(zeroline=False, domain=[0, 0.85], showgrid=False),
        xaxis2=dict(zeroline=False, domain=[0.85, 1], showgrid=False),
        yaxis2=dict(zeroline=False, domain=[0.85, 1], showgrid=False),
        height=700,
        width=700,
        bargap=0,
        hovermode="closest",
        showlegend=False,
    )

    if show_plot:
        fig.show()

    if save_plot:
        fig.write_html(f"{save_folder}/{model_name}_comparison_both_probabilities.html")
Exemplo n.º 25
0
fighters_df = fighter_service.getFightersDF()

xs = fighters_df["Reach_cms_ratio"]
xs = xs[(xs.quantile(0.05) < xs) & (xs < xs.quantile(0.95))]

ys = fighters_df["Height_cms_ratio"]
ys = ys[(ys.quantile(0.05) < ys) & (ys < ys.quantile(0.95))]

zs = fighters_df["is_winner"].replace({False: -1, True: 1})

fig = go.Figure(
    go.Histogram2dContour(
        x=xs,
        y=ys,
        z=zs,
        ncontours=20,
        colorscale="Hot",
        showscale=False,
    ), )
fig.update_layout({
    "title": "Reach and Number of Significant Strikes vs Winner",
})
fig.update_xaxes(title_text="Reach Ratio")
fig.update_yaxes(title_text="Height Ratio")

column2 = dbc.Col([
    dcc.Graph(figure=fig),
], )

layout = dbc.Row([column1, column2])
Exemplo n.º 26
0
import pandas as pd
import plotly.graph_objects as go
import numpy as np

df = pd.read_csv('clean_data.csv', index_col=[0])

x = df.rcb_baseline
y = df.lrfs

fig = go.Figure()
fig.add_trace(
    go.Histogram2dContour(x=x,
                          y=y,
                          colorscale='Blues',
                          reversescale=True,
                          xaxis='x',
                          yaxis='y'))
fig.add_trace(
    go.Histogram(y=y, xaxis='x2', nbinsx=50, marker=dict(color='#1F3451')))
fig.add_trace(
    go.Histogram(x=x, yaxis='y2', nbinsx=50, marker=dict(color='#1F3451')))

fig.update_layout(autosize=False,
                  xaxis=dict(zeroline=False, domain=[0, 0.85], showgrid=False),
                  yaxis=dict(zeroline=False, domain=[0, 0.85], showgrid=False),
                  xaxis2=dict(zeroline=False, domain=[0.85, 1],
                              showgrid=False),
                  yaxis2=dict(zeroline=False, domain=[0.85, 1],
                              showgrid=False),
                  height=800,
                  width=800,
Exemplo n.º 27
0
    def histogram2d(x_data, y_data, f):
        t = np.linspace(-1, 1.2, 2000)
        x = (t ** 3) + (0.3 * np.random.randn(2000))
        y = (t ** 6) + (0.3 * np.random.randn(2000))

        fig = go.Figure()
        fig.add_trace(go.Histogram2dContour(
            x=x,
            y=y,
            colorscale='Blues',
            reversescale=True,
            xaxis='x',
            yaxis='y'
        ))
        fig.add_trace(go.Scatter(
            x=x,
            y=y,
            xaxis='x',
            yaxis='y',
            mode='markers',
            marker=dict(
                color='rgba(0,0,0,0.3)',
                size=3
            )
        ))
        fig.add_trace(go.Histogram(
            y=y,
            xaxis='x2',
            marker=dict(
                color='rgba(0,0,0,1)'
            )
        ))
        fig.add_trace(go.Histogram(
            x=x,
            yaxis='y2',
            marker=dict(
                color='rgba(0,0,0,1)'
            )
        ))

        fig.update_layout(
            autosize=False,
            xaxis=dict(
                zeroline=False,
                domain=[0, 0.85],
                showgrid=False
            ),
            yaxis=dict(
                zeroline=False,
                domain=[0, 0.85],
                showgrid=False
            ),
            xaxis2=dict(
                zeroline=False,
                domain=[0.85, 1],
                showgrid=False
            ),
            yaxis2=dict(
                zeroline=False,
                domain=[0.85, 1],
                showgrid=False
            ),
            height=800,
            width = 1000,
            bargap=0,
            hovermode='closest',
            showlegend=False
        )
        plot_div = plot(fig, output_type='div', include_plotlyjs=True)
        return plot_div
Exemplo n.º 28
0
    def plot2D(raw_data: Dict[str, np.array], x_support: np.array,
               y_support: np.array, features: List[int], spread: float,
               labels: List[str], color_map: Dict[str, str]) -> go.Figure:

        input_data: List[np.array] = [
            raw_data[lab][:, features] for lab in labels
        ]

        def gk_grid(obs: np.array, x_support: np.array, y_support: np.array,
                    spread: float) -> np.array:
            out: np.array = np.zeros((len(x_support), len(y_support)))

            for i, x in enumerate(x_support):
                for j, y in enumerate(y_support):
                    pgk: float = Parzen.gaussian_kernel(
                        np.array([obs]).reshape(1, 2), np.array([[x, y]]),
                        spread)
                    # print(pgk)
                    out[i, j] = pgk
            return out

        def class_density(feature_arr: np.array, x_support: np.array,
                          y_support: np.array, spread: float) -> np.array:
            arrs: List[np.array] = list(
                map(lambda obs: gk_grid(obs, x_support, y_support, spread),
                    feature_arr))
            sum_array: np.array = reduce(lambda f, s: f + s, arrs)
            return sum_array / len(feature_arr)

        contour_data: List[np.array] = [
            class_density(arr, x_support, y_support, spread)[0]
            for arr in input_data
        ]
        consolidated_contour: np.array = reduce(lambda f, s: f + s,
                                                contour_data)
        colors: List[str] = [color_map[lab] for lab in labels]
        contour_colors: List[str] = ["Reds", "Blues", "Greens"]

        fig: go.Figure = go.Figure()
        # fig.add_trace(go.Contour(
        #     z = contour_data[0],
        #     x = x_support,
        #     y = y_support
        # ))
        for i, lab in enumerate(labels):
            fig.add_trace(
                go.Histogram2dContour(
                    x=[input_data[i][j][0] for j in range(len(input_data[i]))],
                    y=[input_data[i][j][1] for j in range(len(input_data[i]))],
                    colorscale=contour_colors[i]))
            fig.add_trace(
                go.Scatter(
                    x=[input_data[i][j][0] for j in range(len(input_data[i]))],
                    y=[input_data[i][j][1] for j in range(len(input_data[i]))],
                    mode="markers",
                    opacity=0.7,
                    marker=dict(color="#ffffff",
                                line=dict(color=colors[i], width=3)),
                    name=f"{lab} data"))

        fig.update_layout(template="plotly_white")
        return fig
Exemplo n.º 29
0
# ----------------
t = np.linspace(-1, 1.2, 2000)
x = (t**3) + (0.3 * np.random.randn(2000))
y = (t**6) + (0.3 * np.random.randn(2000))

# ----------------
# Create figure
# ----------------
fig = go.Figure()
fig.add_trace(
    go.Histogram2dContour(
        x=x,
        y=y,
        colorscale='Blues',  # 'Jet'
        contours=dict(showlabels=True,
                      labelfont=dict(family='Raleway', color='white')),
        hoverlabel=dict(bgcolor='white',
                        bordercolor='black',
                        font=dict(family='Raleway', color='black')),
        reversescale=True,
        xaxis='x',
        yaxis='y'))
fig.add_trace(
    go.Scatter(x=x,
               y=y,
               xaxis='x',
               yaxis='y',
               mode='markers',
               marker=dict(color='rgba(0,0,0,0.3)', size=3)))
fig.add_trace(go.Histogram(y=y, xaxis='x2',
                           marker=dict(color='rgba(0,0,0,1)')))
fig.add_trace(go.Histogram(x=x, yaxis='y2',
Exemplo n.º 30
0
for filename in all_files:
    _df = pd.read_csv(filename, comment="#", header=None)
    li.append(_df)

_data = pd.concat(li, axis=0)
data = _data[[1, 7, 11]]
data.columns = ["gamma", "CE", "beta"]

# Only get values in coincidence & when gamma = 31.6 keV and CE is between 0.04 and 0.5
data = data[(data["gamma"] == 0.0316)]
data = data[(data["CE"] > 0)]
data = data[(data["beta"] > 0)]

fig = go.Figure()
fig.add_trace(
    go.Histogram2dContour(x=data["CE"], y=data["beta"], colorscale='Blues'))
fig.add_trace(
    go.Histogram(y=data["beta"],
                 xaxis='x2',
                 marker=dict(color='rgba(63,121,181,1)')))
fig.add_trace(
    go.Histogram(x=data["CE"],
                 yaxis='y2',
                 marker=dict(color='rgba(63,121,181,1)')))
fig.update_layout(
    autosize=False,
    xaxis=dict(zeroline=False, domain=[0, 0.8], showgrid=False),
    yaxis=dict(zeroline=False, domain=[0, 0.8], showgrid=False),
    xaxis2=dict(zeroline=False, domain=[0.83, 1], showgrid=False),
    yaxis2=dict(zeroline=False, domain=[0.85, 1], showgrid=False),
    height=600,