Example #1
0
def dash_report():
    import pandas as pd
    import plotly
    import dash
    import dash_table
    import plotly.express as px
    import dash_core_components as dcc
    import dash_html_components as html
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context

    app = dash.Dash(__name__)

    df4 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')

    c = df4.columns

    fig1 = px.bar(df4, x=df4.iloc[:, 1], y=df4.iloc[:, 2], hover_data=df4.columns, color=c[3],
                  labels={'x': c[1], 'y': c[2]})

    fig2 = px.scatter(df4, x=df4.iloc[:, 1], y=df4.iloc[:, 2], height=700, hover_data=df4.columns, color=c[3],
                      size=df4.iloc[:, 4], size_max=65, log_x=True, labels={'x': c[1], 'y': c[2]})

    fig3 = px.line(df4, x=df4.iloc[:, 1], y=df4.iloc[:, 2], color=c[3], line_group=c[0], hover_name=c[0])

    fig4 = px.density_heatmap(df4, x=df4.iloc[:, 1], y=df4.iloc[:, 4], nbinsx=20, nbinsy=20,
                              labels={'x': c[1], 'y': c[4]}, hover_data=df4.columns)

    fig5 = px.density_heatmap(df4, x=df4.iloc[:, 1], y=df4.iloc[:, 4], nbinsx=10, nbinsy=10, facet_row=df4.iloc[:, 3],
                              labels={'x': c[1], 'y': c[4]}, hover_data=df4.columns)

    fig6 = px.treemap(df4, path=[df4.iloc[:, 1], df4.iloc[:, 3]], values=df4.iloc[:, 2], color=df4.iloc[:, 1],
                      color_continuous_scale=['red', 'yellow'])

    plotly.offline.plot(fig6, filename='C:\\Ashwin\\SparkCode\\projects\\CodeWeek\\genie\\SR\\templates\\fig6.html')
Example #2
0
def create_analysis_heatmap(yType, lsoa_selected):

    if 'All' in lsoa_selected:
        lsoa_selected = sectors

    df_lsoa_selected, df_stores_selected = create_analysis_data(lsoa_selected)
    df_display = df_stores_selected.merge(df_lsoa_selected[['LSOA', 'IMDRank', 'IMDDecile']], how='right', on='LSOA')
    df_display.sort_values(by = ['IMDRank', 'Healthfulness'], inplace=True, ascending=False, ignore_index=True)
    title = 'Store Distribution'
    if yType == 0:
        fig = px.density_heatmap(df_display, x='Healthfulness', y='LSOA', marginal_x='histogram',
                                 color_continuous_scale=px.colors.sequential.Viridis)
    elif yType == 1:
        fig = px.density_heatmap(df_display, x='Healthfulness', y='IMDDecile', marginal_x='violin',
                                 marginal_y='violin', color_continuous_scale=px.colors.sequential.Viridis)
        fig.update_yaxes(range = [-1, 12])
    else:
        fig = go.Figure()

    fig.update_layout(plot_bgcolor=colors['background'],
                      paper_bgcolor=colors['background'],
                      autosize=True,
                      height = 450,
                      #margin={'l': 20, 'b': 30, 'r': 10, 't': 40},
                      coloraxis_colorbar=dict(
                          title="Number of Stores",
                          thicknessmode="pixels", thickness=20,
                          yanchor="top", y=1,
                          ticks="outside"
                      ),
                      font_color=colors['font'])
    fig.update_xaxes(range = [-2, 2])
    # fig.update_yaxes(title = 'LSOA (Arranged IMDRank)')
    return fig
Example #3
0
def plot_corner_cases(corner_cases, summary, special=None, CORNER_LIMIT=.1):
    prefix = 'ALL'
    if special is True:
        prefix = 'Special Only'
        corner_cases = corner_cases[corner_cases.spec].copy()
    elif special is False:
        prefix = 'NOT Special Only'
        corner_cases = corner_cases[~corner_cases.spec].copy()

    print(
        f'Plotting results for {len(corner_cases)} corner cases for {summary["nb_samples"]} samples.'
    )
    print(
        f'Corner cases are happening for {len(corner_cases.i.unique()) / summary["nb_samples"] * 100}% of the rejected cutomers'
        f'Corner cases with perc_shift < 10% are happening for {len(corner_cases[corner_cases.perc_shift < CORNER_LIMIT].i.unique()) / summary["nb_samples"] * 100}% of the rejected cutomers'
    )

    fig = px.histogram(
        corner_cases,
        x='Feature',
        title=f'{prefix} - AAR SHAP Corner - Cases Features',
        hover_data=corner_cases.columns,
    )
    fig.update_layout(yaxis=dict(tickformat=',.2%', ), )
    fig.show()
    # fig = go.Figure([go.Bar(
    #     x=features_names,
    #     y=summ['corner_rate'],
    # )])
    # fig.update_layout(
    #     title=f'{prefix} - AAR SHAP Corner - Cases Features Rate (percentage)',
    #     yaxis=dict(tickformat=',.0%', ),
    # )
    # fig.show()

    px.histogram(
        corner_cases,
        x='perc_shift',
        title=f'{prefix} - AAR SHAP Corner Cases - Percentile Shifts',
        hover_data=corner_cases.columns,
    ).show()

    px.density_heatmap(
        corner_cases,
        x='Feature',
        y='perc_shift',
        nbinsy=50,
        title=f'{prefix} - AAR SHAP Corner Cases',
    ).show()

    px.density_heatmap(
        corner_cases[corner_cases.perc_shift < CORNER_LIMIT],
        x='Feature',
        y='perc_shift',
        nbinsy=50,
        title=f'{prefix} - AAR SHAP Corner Cases / ONLY with perc_shift < 10%',
    ).show()
Example #4
0
def test_auto_histfunc():
    a = [1, 2]
    assert px.histogram(x=a).data[0].histfunc is None
    assert px.histogram(y=a).data[0].histfunc is None
    assert px.histogram(x=a, y=a).data[0].histfunc == "sum"
    assert px.histogram(x=a, y=a, histfunc="avg").data[0].histfunc == "avg"

    assert px.density_heatmap(x=a, y=a).data[0].histfunc is None
    assert px.density_heatmap(x=a, y=a, z=a).data[0].histfunc == "sum"
    assert px.density_heatmap(x=a, y=a, z=a, histfunc="avg").data[0].histfunc == "avg"
Example #5
0
def get_experiment_digest(experiment: pd.DataFrame):
    df = experiment.copy()

    if df.shape[0] > 0:
        temp_date_time = pd.DatetimeIndex(df["date_time"])
        df.insert(loc=4, column="time", value=temp_date_time.time)
        df.insert(loc=4, column="date", value=temp_date_time.date)

        df["hour"] = pd.to_numeric(
            df.time.astype("str").str.split(pat=":", expand=True).iloc[:, 0]
        ).to_list()

        count = df.shape[0]

        desc_lines = {
            f"{col.replace('_', ' ').capitalize()}s": f"{len(list(df[col].unique()))} unique"
            for col in ["Plant", "date", "Camera", "view_option"]
        }

        fig = px.density_heatmap(
            title="Observations per day and hour",
            data_frame=df,
            x="date",
            y="hour",
            height=400,
        )
        fig.update_yaxes(tick0=-0.5)
    else:
        count = 0
        desc_lines = {col: "None" for col in ["plant", "date", "camera", "view_option"]}
        fig = None

    return count, desc_lines, fig
Example #6
0
def get_figure(df):
    # for an explanation
    fig = px.density_heatmap(df)

    fig.update_layout(width=500, height=500, margin=dict(l=20, r=0, t=15, b=5))

    return fig
Example #7
0
def build_graphBB1(dff,x_axis, y_axis,mode,trendline, marginal_sel,color,facet):
    if marginal_sel == "None": marginal_sel = None
    if color == "None": color = None
    if facet == "None": facet = None
    
    if trendline == "Ordinary Least Squares Regression": trendline = 'ols'
    elif trendline == "Locally Weighted Smoothing": trendline = 'lowess'
    

    fig = go.Figure()
    if mode == "Scatter":
        fig = px.scatter(dff, x=x_axis, y=y_axis, color=color, facet_col=facet, facet_col_wrap=3,
                        marginal_y=marginal_sel, marginal_x=marginal_sel, trendline="ols")
    if mode == "Heat":
        fig = px.density_heatmap(dff, x=x_axis, y=y_axis, marginal_x=marginal_sel, marginal_y=marginal_sel)
    if mode == "Density":
        #fig = px.density_contour(df, x="total_bill", y="tip", marginal_x=marginal_x, marginal_y=marginal_y)
        fig = px.density_contour(dff, x=x_axis, y=y_axis, color=color, marginal_x=marginal_sel,
                                 marginal_y=marginal_sel, trendline=trendline)
    if mode == "Density Fill":
        fig = px.density_contour(dff, x=x_axis, y=y_axis)
        fig.update_traces(contours_coloring="fill", contours_showlabels = True)
    
    
    fig.update_layout(
            #margin=dict(l=0, r=0, t=0, b=0),
            #paper_bgcolor="lightcyan",
            #plot_bgcolor='gainsboro' #gainsboro, lightsteelblue lightsalmon lightgreen lightpink lightcyan lightblue black
        )


    graph = dcc.Graph(id="scatterB", figure=fig)


    return graph
Example #8
0
 def make_heatmap(**params):
     if params['hist_x']:
         params['hist_x'] = "histogram"
     else:
         params['hist_x'] = None
     if params['hist_y']:
         params['hist_y'] = "histogram"
     else:
         params['hist_y'] = None
     fig = px.density_heatmap(
         df,
         x=Xs[-1],
         y=Y,
         marginal_x=params['hist_x'],
         marginal_y=params['hist_y'],
         title=params['Title'],
         width=params['Figsize_x'] * 100,
         height=params['Figsize_y'] * 100,
     )
     fig.update_layout(
         xaxis_title=params['xlabel'],
         yaxis_title=params['ylabel'],
     )
     fig.show()
     if params['save']:
         fig.write_image("saved_plotly_heatmap.png")
Example #9
0
def DiversityMap():
    fig = px.density_heatmap(HR_df,
                             x="Position",
                             y="RaceDesc",
                             facet_row="Sex")

    return fig.write_html(
        "/Users/christiannielsen/Documents/GitHub/christiannielsen98.github.io/docs/Python/HTML/DiversityMap.html"
    )
Example #10
0
def g8(batch_id, x, y, colorset):
    input_model = models.BatchInput(batch_id)
    df = input_model.as_pandas_dataframe()

    fig = px.density_heatmap(df, x=x, y=y, marginal_x="rug", marginal_y="histogram",
        color_continuous_scale=get_colorset(colorset))
    div = opy.plot(fig, auto_open=False, output_type='div')

    return div
Example #11
0
def log_plotly(step):
    df = px.data.tips()

    fig = px.density_heatmap(df,
                             x="total_bill",
                             y="tip",
                             facet_row="sex",
                             facet_col="smoker")
    tracking.log_plotly_chart(name="2d-hist", figure=fig, step=step)
Example #12
0
def analyze(plot_against_income):
    fig = px.density_heatmap(_data, x=plot_against_income, y="V2026")
    fig = px.density_heatmap(
        _data,
        x=plot_against_income,
        y="V2026",
        title='<b>Expected Income</b>\r\n(Hover for details)',
        height=400,
        width=400,
        nbinsx=pd.Series(_data[plot_against_income]).nunique(),
        nbinsy=pd.Series(_data['V2026']).nunique(),
        range_color=heatmap_z_min_max(fig))
    fig.layout['xaxis']['title']['text'] = mf.dataDictionary[
        plot_against_income]['Desc'].capitalize()
    fig.layout['yaxis']['title']['text'] = 'Income Bracket'
    fig.layout['coloraxis']['colorbar']['title']['text'] = 'Count'
    graph = dcc.Graph(figure=fig)
    return graph
Example #13
0
def heatmap(df: pd.DataFrame, x: str, y: str, criteria: str = None) -> go.Figure:
    if criteria is not None:
        df = filter_records(df, criteria)
    if not x in df.columns:
        logger.log_error('x not found in columns')
        return
    if not y in df.columns:
        logger.log_error('y not found in columns')
        return
    return px.density_heatmap(df, x=x, y=y)
Example #14
0
def plotting(data):
    # scatter plot of petal lengths vs. petal widths
    petal_length_v_width_plot = px.scatter(data, x=2, y=3)
    petal_length_v_width_plot.update_layout(
        title_text="petal lengths vs. petal widths")
    petal_length_v_width_plot.update_xaxes(ticks="inside",
                                           title_text="Petal Lengths (cm)")
    petal_length_v_width_plot.update_yaxes(ticks="inside",
                                           title_text="Petal Widths (cm)")

    # violin plot of sepal lengths
    # sepal_lengths_violin_plot = px.violin(data, y=0:4)

    sepal_lengths_violin_plot = px.violin(data,
                                          y=0,
                                          color=4,
                                          violinmode="overlay")
    sepal_lengths_violin_plot.update_layout(
        title_text="violin plot of sepal lengths", )
    sepal_lengths_violin_plot.update_yaxes(title_text="sepal length (cm)")

    # pie chart of different classes observed
    setosa = data[:, 4].tolist().count("Iris-setosa")
    versicolor = data[:, 4].tolist().count("Iris-versicolor")
    virginica = data[:, 4].tolist().count("Iris-virginica")
    labels = ["Setosa", "Versicolor", "Virginica"]
    values = [setosa, versicolor, virginica]
    pie_chart_classes = go.Figure(data=[
        go.Pie(
            labels=labels,
            values=values,
            textinfo="label+text+value+percent",
            insidetextorientation="auto",
            hole=0.3,
        )
    ])

    # box plot of petal lengths of each class
    box_plot_of_petal_lengths = px.box(data, x=4, y=2, points="all")
    box_plot_of_petal_lengths.update_xaxes(title="Unique Species")
    box_plot_of_petal_lengths.update_yaxes(title="Petal Lengths (cm)")

    # 2-D histogram (heatmap) of petal width and sepal width
    hist_2d = px.density_heatmap(data, x=3, y=1)
    hist_2d.update_xaxes(title="Petal Width (cm)")
    hist_2d.update_yaxes(title="Sepal Width (cm)")

    # show plots
    petal_length_v_width_plot.show()
    sepal_lengths_violin_plot.show()
    pie_chart_classes.show()
    box_plot_of_petal_lengths.show()
    hist_2d.show()
    return
Example #15
0
def signal_heatmap_plot(cluster_pd_2D_pre_2, sel_binning):
    fig = px.density_heatmap(x=cluster_pd_2D_pre_2.cl_pos_x,
                             y=cluster_pd_2D_pre_2.cl_pos_y,
                             marginal_x="histogram",
                             marginal_y="histogram",
                             nbinsx=int(128 / sel_binning),
                             nbinsy=int(128 / sel_binning))
    fig.update_layout(yaxis_title="Y strips ",
                      xaxis_title="X strips",
                      height=800)
    return fig
Example #16
0
def genre_year_position_heatmap(genre_per_act_df, smooth, category_orders):
    # Position on lineup x Musical Genre
    df = genre_per_act_df.copy()

    binsize = int(100 / smooth)

    df.loc[:, 'importance_order'] = df['order_in_lineup'].apply(
        lambda x: min([x // binsize, smooth - 1]))
    df.loc[:, 'importance_order'] = df['importance_order'].apply(lambda x: "{:.0f}%-{:.0f}%".format(x*binsize, (x+1)*binsize)\
                                                                if x < smooth - 1 else "{:.0f}%-100%".format(x*binsize))
    df = df.sort_values('importance_order')

    df.loc[:, 'value'] = 100 * df['value']

    df.loc[:,
           'rank_on_order'] = df.groupby(['importance_order', 'genre', 'year'
                                          ])['value'].rank(ascending=False)

    df_artists = df\
                    .loc[df['rank_on_order'] <= 5]\
                    .groupby(['genre', 'importance_order', 'year'])['artist_name'].apply(lambda x: '<br>'.join(x))\
                    .to_frame().reset_index()

    df = df\
            .groupby(['genre', 'importance_order', 'year'], as_index=False)\
            .agg({'value':'mean'})

    df = pd.merge(left=df,
                  right=df_artists,
                  on=['year', 'genre', 'importance_order'],
                  how='left')

    fig = px.density_heatmap(df,
                             animation_frame='genre',
                             z='value',
                             y='importance_order',
                             hover_data=['artist_name'],
                             category_orders=category_orders,
                             x='year',
                             color_continuous_scale=px.colors.sequential.RdPu,
                             nbinsx=9,
                             range_color=[0, 50])

    fig = format_fig(fig)

    fig.update_layout(
        title=
        'Evolução da relevância de cada gênero musical por horário do Lineup',
        coloraxis_colorbar_title='Participação<br>',
        coloraxis_colorbar_ticksuffix='%',
        coloraxis_colorbar_tickvals=[0, 15, 30, 45])

    return fig
Example #17
0
def update_grad_yr_histogram(selected_country):
    filtered_df = df_grad_years[df_grad_years["COUNTRY_ISO"] ==
                                selected_country]
    maxyr = df_grad_years["YEAR"].max()

    fig = px.density_heatmap(filtered_df, 
                             x="FOREIGN_WORKER_YRS_ED_COMP",
                             y="YEAR", z="COUNT",
                             range_x=[1980, maxyr])
    fig.update_traces(xbins_size=1)

    return fig
 def basic_image(self):
     """Create a heat-map plot and update the figure attribute. Requires that x, y and z attributes are set.
     z must be a 2D image.
     """
     self.figure = px.density_heatmap(
         self.data,
         x=self.x,
         y=self.y,
         z=self.z,
         color_continuous_scale=px.colors.sequential.Viridis,
         hover_data=self.labels,
     )
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [{
        'data': [Bar(x=genre_names, y=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }]

    df['summ'] = df[df.columns[4:]].sum(axis=1)

    fig = px.density_heatmap(
        df,
        x="genre",
        y="summ",
        marginal_x="histogram",
        marginal_y="histogram",
        labels={
            "genre": "Message genre",
            "summ": "Number of categories each message is classified as"
        },
        title="Density heatmap of message category vs genre")
    graphs.append(fig)

    fig = px.imshow(
        df[df.columns[4:-1]],
        labels=dict(x="Message category",
                    y="Message number",
                    color="classified as"),
        title='Visualization of the categories, each message is classified as')

    graphs.append(fig)

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Example #20
0
def graf_ods_2(local):
    df = ROYALTIES
    local = trata_local(local)
    if len(local) > 0:
        df = df.loc[df['municipio'].isin(local)]
    fig = px.density_heatmap(df,
                             x='ano',
                             z='royalties per capita',
                             y="municipio",
                             hover_data=['municipio', 'ano'],
                             title="Graf. 1 - Metas ODS")
    fig.update_layout(xaxis=dict(tickmode='linear', dtick=1))
    return fig
Example #21
0
def update_graph(events_json, player, value) :
    if player :
        events = pd.read_json(events_json, orient='split')
        player_events = events[events["player"] == player]
        
        newxbins = math.floor(120 / value)
        newybins = math.floor(80 / value)
        print("loc_x: ")
        print(player_events["loc_x"])
        
        return px.density_heatmap(player_events, x="loc_x", y="loc_y", nbinsx=newxbins, nbinsy=newybins, color_continuous_scale="Viridis")
    else :
        return {}
Example #22
0
    def get_html(cfg, mode=None):
        df = HeatMap.compute()

        fig = px.density_heatmap(df,
                                 y="Rolle-Kontext",
                                 x="Gesamtbewertung",
                                 nbinsy=20,
                                 color_continuous_scale="Viridis")
        fig.update_layout(title="Verteilung Teilnehmer",
                          paper_bgcolor='rgb(243, 243, 243)',
                          plot_bgcolor='rgb(243, 243, 243)')

        return fig.to_html(**cfg)
Example #23
0
def doTomography(bins, mdf, title):
    fig = px.density_heatmap(mdf,
                             x="xx",
                             y="yy",
                             title=title,
                             nbinsx=bins,
                             nbinsy=bins,
                             marginal_x="histogram",
                             marginal_y="histogram")
    fig.update_layout(
        xaxis_title="XView (cm)",
        yaxis_title="YView (cm)",
    )
    fig.show()
Example #24
0
def signal_heatmap_plot(cluster_pd_2D_pre_2, sel_binning):
    fig = px.density_heatmap(
        x=cluster_pd_2D_pre_2.cl_pos_x * 0.0650,
        y=cluster_pd_2D_pre_2.cl_pos_y * 0.0650,
        marginal_x="histogram",
        marginal_y="histogram",
        nbinsx=int(128 / sel_binning),
        nbinsy=int(128 / sel_binning),
        color_continuous_scale=px.colors.sequential.Viridis)
    fig.update_layout(yaxis_title="Y pos [cm] ",
                      xaxis_title="X pos [cm]",
                      height=800,
                      width=800)
    return fig
Example #25
0
def get_figure5(df, x_col, y_col):
    print("HEATMAP")
    print(df)
    fig = px.density_heatmap(df,
                             x=x_col,
                             y=y_col,
                             marginal_x="histogram",
                             marginal_y="histogram")
    fig.update_layout(autosize=True,
                      margin=dict(l=30, r=30, b=20, t=40),
                      hovermode="closest",
                      plot_bgcolor="#F9F9F9",
                      paper_bgcolor="#E9E9E9",
                      legend=dict(font=dict(size=10), orientation="h"))
    return fig
Example #26
0
def charge_vs_time_plot(hit_pd_APV):
    fig = px.density_heatmap(hit_pd_APV,
                             x="GemHit_time",
                             y="GemHit_q",
                             title="Charge vs time",
                             marginal_x="histogram",
                             marginal_y="histogram",
                             color_continuous_scale=colorscale,
                             nbinsx=150,
                             nbinsy=150)
    fig.update_layout(xaxis_title="Time ",
                      yaxis_title="Charge [adc]",
                      height=800)
    # fig.update_xaxes(range=[1300, 1600])
    # fig.update_yaxes(range=[0, 60])
    return fig
Example #27
0
def showgraph(graph_selection, liste_annee, liste_ville, liste_specialite):
    if graph_selection == "Carte Thermique":
        df = pd.read_csv('data/2_aggregates/agg_latest_spot.csv', index_col=0)
        df = df[df.ville.isin(liste_ville)
                & df.specialite.isin(liste_specialite)
                & df.annee.isin(liste_annee)]

        fig = px.density_heatmap(df,
                                 x="ville",
                                 y="specialite",
                                 z="classement",
                                 histfunc="avg")
        st.plotly_chart(fig, use_container_width=True)

    if graph_selection == "Boites à Moustaches":
        st.write("WIP")

    if graph_selection == "Résulats par Ville à travers le temps":
        df = df.groupby(['ville', 'annee']).max()
        df = df.reset_index(level=['ville', 'annee'])
        st.write(df)

        fig = px.line(df, x="annee", y="classement", color='ville')
        st.plotly_chart(fig, use_container_width=True)

    if graph_selection == "Résulats par Spécialité à travers le temps":
        fig = px.line(df, x="annee", y="classement", color='specialite')
        st.plotly_chart(fig, use_container_width=True)

    if graph_selection == "Lignes de crêtes par Ville":
        df_full = pd.read_csv('data/2_aggregates/full.csv', index_col=0)
        df_full = df_full[df_full.ville.isin(liste_ville)
                          & df_full.specialite.isin(liste_specialite)
                          & df_full.annee.isin(liste_annee)]
        plt.figure()
        joyplot(data=df_full[['classement', 'ville']],
                by='ville',
                figsize=(12, 8),
                linecolor="blue",
                colormap=cm.autumn_r)
        plt.title('Ligne de crête des classements par ville', fontsize=20)
        st.pyplot(plt, use_container_width=True)

    if graph_selection == "Lignes de crêtes par Spécialité":
        st.write("WIP")
Example #28
0
def fig_density_heatmap(df,
                        df_x,
                        df_y,
                        title,
                        marginal_x=None,
                        marginal_y=None):
    """
    Density heatmap for the first feature of the dataframe
    """
    fig = px.density_heatmap(
        df,
        x=df_x,
        y=df_y,
        marginal_x=marginal_x,
        marginal_y=marginal_y,
        title=title,
    )
    fig = fig_update_layout(fig)
    return fig
def interactive_heatmap2D(df):
    """
  Interactive Histogram2D Plot
  
  params: 
    df: input data frame
    
  return:
    plots histogram2D plot in streamlit
  
  """

    global column2idx
    # Choose X, Y and Color Axis
    cols = st.beta_columns([1, 3])
    with cols[0]:
        st.markdown("### X-axis")
        x_col = st.selectbox("Choose X-Axis Feature", df.columns,
                             column2idx["age"])
        nbinsx = st.slider("Number of Bins", 10, 100, 20)

        st.markdown("### Y-axis")
        y_col = st.selectbox("Choose Y-Axis Feature", df.columns,
                             column2idx["fnlwgt"])
        nbinsy = st.slider("Number of Bins (Y-Axis)", 10, 100, 20)

        st.markdown("### Z-axis")
        z_col = st.selectbox("Choose Z-Axis Feature", df.columns,
                             column2idx["hours_per_week"])
        agg_func = st.selectbox("Aggregation Function",
                                ["avg", "sum", "min", "sum", "count"], 0)

    with cols[1]:

        fig = px.density_heatmap(df,
                                 x=x_col,
                                 y=y_col,
                                 z=z_col,
                                 nbinsx=nbinsx,
                                 nbinsy=nbinsy,
                                 histfunc=agg_func)
        fig.update_layout(width=1000, height=800, font_size=20)
        st.plotly_chart(fig)
    def scatter_browser_dimensions(self,
                                   df,
                                   type_plot='scatter',
                                   save_file=True):
        """
        Output scatter plot of browser dimensions.

        Args:
            df (dataframe): dataframe with data from heroku.
            type_plot (str, optional): type of plot: scatter, density_heatmap.
            save_file (bool, optional): flag for saving an html file with plot.
        """
        logger.info('Creating plot of type_plot %s for browser dimensions.',
                    type_plot)
        # scatter plot with histograms
        if type_plot == 'scatter':
            fig = px.scatter(df,
                             x='window_width',
                             y='window_height',
                             marginal_x='violin',
                             marginal_y='violin',
                             color='browser_name')
        # density map with histograms
        elif type_plot == 'density_heatmap':
            fig = px.density_heatmap(df,
                                     x='window_width',
                                     y='window_height',
                                     marginal_x='violin',
                                     marginal_y='violin')
        # unsopported type
        else:
            logger.error('Wrong type of plot %s given.', type_plot)
            return -1

        # update layout
        fig.update_layout(template=self.template)
        # save file
        if save_file:
            self.save_plotly(fig, 'scatter_browser_dimensions', self.folder)
        # open it in localhost instead
        else:
            fig.show()