Ejemplo n.º 1
0
def make_plots(combined_stats):

    ## Make figures with PLOTLY
    # load and rename data
    df = pd.read_csv(combined_stats, sep="\t", index_col=0)
    df.sort_index(ascending=True, inplace=True)
    df.index.name = "Sample"
    df["Sample"] = df.index

    # create plots store in div
    div = {}

    fig = px.strip(df, y="Percent_Assembled_Reads", hover_name="Sample", **PLOT_PARAMS)
    fig.update_yaxes(range=[0, 100])
    div["Percent_Assembled_Reads"] = fig.to_html(**HTML_PARAMS)

    fig = px.strip(df, y="N_Predicted_Genes", hover_name="Sample", **PLOT_PARAMS)
    div["N_Predicted_Genes"] = fig.to_html(**HTML_PARAMS)

    fig = px.scatter(df, y="L50", x="N50", hover_name="Sample", **PLOT_PARAMS)
    div["N50"] = fig.to_html(**HTML_PARAMS)

    fig = px.scatter(df, y="L90", x="N90", hover_name="Sample", **PLOT_PARAMS)
    div["N90"] = fig.to_html(**HTML_PARAMS)

    fig = px.scatter(
        df, y="contig_bp", x="n_contigs", hover_name="Sample", **PLOT_PARAMS
    )
    div["Total"] = fig.to_html(**HTML_PARAMS)

    return div
Ejemplo n.º 2
0
    def character_appearances(self, movie_characters):

        scene_number = []
        xters = []
        sc_num = 0
        for x in range(len(self.df_movie)):
            sc_num += 1
            for y in movie_characters:
                if self.df_movie['Scene_Characters'][x]:
                    if y in self.df_movie['Scene_Characters'][x]:
                        xters.append(y)
                        scene_number.append(sc_num)
        df_app = pd.DataFrame(list(zip(xters, scene_number)),
                              columns=['characters', 'Scene Numbers'])

        fig = px.strip()
        fig['layout']['yaxis']['autorange'] = "reversed"
        fig = px.strip(data_frame=df_app,
                       x='Scene Numbers',
                       y='characters',
                       hover_data=df_app.columns,
                       color='characters',
                       labels={'characters': '<b> Scene Characters <b>'},
                       width=1000,
                       height=800)
        #fig['layout']['yaxis']['autorange'] = "reversed"
        fig.update_layout(
            title=
            '<b> Appearances of characters ordered by their first appearance, in the '
            + self.movie + ' movie <b>',
            xaxis_title='<b> Scene Numbers <b>',
            yaxis_title='<b> Scene Characters <b>')
        iplot(fig)

        return df_app
Ejemplo n.º 3
0
def make_plots(bin_table):

    div = {}

    div["input_file"] = bin_table

    # Prepare data
    df = pd.read_table(bin_table)
    df.index = df["Bin Id"]
    df = df.join(tax2table(df["Taxonomy (contained)"], remove_prefix=True).fillna("NA"))

    df["Quality Score"] = df.eval("Completeness - 5* Contamination")

    div[
        "QualityScore"
    ] = "<p>Quality score is calculated as: Completeness - 5 x Contamination.</p>"

    # 2D plot
    fig = px.scatter(
        data_frame=df,
        y="Completeness",
        x="Contamination",
        color="phylum",
        size="Genome size (Mbp)",
        hover_data=["genus"],
        hover_name="Bin Id",
    )
    fig.update_yaxes(range=(50, 102))
    fig.update_xaxes(range=(-0.2, 10.1))
    div["2D"] = fig.to_html(**HTML_PARAMS)

    ## By sample
    fig = px.strip(
        data_frame=df,
        y="Quality Score",
        x="Sample",
        color="phylum",
        hover_data=["genus"],
        hover_name="Bin Id",
    )
    fig.update_yaxes(range=(50, 102))
    div["bySample"] = fig.to_html(**HTML_PARAMS)

    # By Phylum
    fig = px.strip(
        data_frame=df,
        y="Quality Score",
        x="phylum",
        hover_data=["genus"],
        hover_name="Bin Id",
    )
    fig.update_yaxes(range=(50, 102))
    div["byPhylum"] = fig.to_html(**HTML_PARAMS)

    return div
Ejemplo n.º 4
0
def plot_subject_grades(selected_names):
    student_name = selected_names[-1]
    student_subjects = clean_df.loc[clean_df['Name'] == student_name]

    student_sub_df = student_subjects[['Subject1',
                                       'Grade1']].rename(columns={
                                           'Subject1': 'Subject',
                                           'Grade1': 'Grade'
                                       })

    for i in range(2, 12):
        student_sub_df = pd.concat([
            student_sub_df, student_subjects[[f'Subject{i}', f'Grade{i}'
                                              ]].rename(columns={
                                                  f'Subject{i}': 'Subject',
                                                  f'Grade{i}': 'Grade'
                                              })
        ],
                                   ignore_index=True)

    student_sub_df = student_sub_df.dropna().drop_duplicates()

    strip_fig = px.strip(student_sub_df,
                         x='Subject',
                         y='Grade',
                         category_orders={
                             'Grade':
                             ['EX', 'A', 'B', 'C', 'D', 'P', 'F', 'X', 'Y']
                         })

    return strip_fig
Ejemplo n.º 5
0
def swarmplot(df, metric, team, dict_metrics):
    import plotly.express as px
    df_filter = df[['Squad', 'Competition', metric]]
    limits = [
        round(np.percentile(df_filter[metric], i), 2)
        for i in range(20, 120, 20)
    ] + [team]
    df_filter['Percentile'] = df_filter[metric].apply(
        lambda x: str([j for j in limits[:-1] if x <= j][0]))
    df_filter.loc[df_filter.Squad == team, 'Percentile'] = team
    colors = ['red', 'coral', 'gold', 'lightgreen', 'forestgreen', 'black']

    #plot
    fig = px.strip(
        data_frame=df_filter,
        x=metric,
        color='Percentile',
        hover_name='Squad',
        hover_data=['Competition', metric],
        color_discrete_sequence=colors,
        color_discrete_map={str(i): j
                            for i, j in zip(limits, colors)},
        stripmode='overlay',
        template='plotly')
    fig.update_layout(showlegend=False,
                      xaxis_title=metric,
                      title=dict_metrics[metric])
    fig.update_yaxes(showticklabels=False)
    return fig
Ejemplo n.º 6
0
def sound_share_strip_by__period(movies_melt_df, sound_color_map):
    # Sound composition, by movie
    df = movies_melt_df.copy()

    df.loc[:, 'period'] = (np.floor(df['year']/20)*20).astype(int)
    df.loc[:, 'period'] = df['period'].apply(lambda x: f"{x}-<br>{x+19}")

    fig = px.strip(df.sort_values(by='period'), y='value', color='var_name',
                facet_col='period', color_discrete_map=sound_color_map,
                hover_name='title', hover_data=['year', 'top_250_rank'])

    fig.update_yaxes(dtick=50, range=[0,110], ticksuffix='%')
    fig.update_xaxes(title='', showticklabels=False)

    fig.update_layout(
        title = 'By which type of sound each movie is composed?', 
        showlegend=True, 
        legend_orientation='h',
        legend_y=-0.1,
        margin_t=120,
        legend_title='Type of sound',
        yaxis_title='')

    fig = facet_prettify(fig)
    fig = format_fig(fig)
    return fig
Ejemplo n.º 7
0
def sound_share_strip_per_genre(movies_melt_df, sound_color_map):
    # Strip details
    df = movies_melt_df.copy()

    df.loc[:, 'genres'] = df['genres'].apply(lambda x: eval(x))

    df = pd.DataFrame.explode(df, column='genres')
    df.loc[:, 'Genre'] = df['genres'].apply(lambda x: "<b>{}</b>".format(x))

    df.loc[:, 'rank_var'] = df.groupby(['genres', 'var_name'])['value'].rank(ascending=False)

    df = df.sort_values(by=['Genre'])

    # df.loc[:, 'text'] = df.apply(lambda x: x['title'] if x['rank_var'] == 1 else  '', axis=1)

    fig = px.strip(df, x='value', animation_frame='Genre', y='var_name', hover_data=['year', 'top_250_rank'],
                hover_name='title', color='var_name', color_discrete_map=sound_color_map
                )
    # fig.update_yaxes(ticksuffix='%', dtick=25, rangemode='tozero', range=[0,101])
    fig.update_xaxes(matches=None, range=[-1,101], dtick=25, ticksuffix='%')

    fig = facet_prettify(fig)
    fig = format_fig(fig)
    fig.update_layout(
        showlegend=False, 
        height=400,
        yaxis_title='Sound type',
        title='Sound distribution, per genre',
        xaxis_title='Share of movie')

    fig = leave_only_slider(fig)
    
    return fig
Ejemplo n.º 8
0
def generate_strip_plot(df):
    """Generates vessel strip plot."""
    hover_dict = {"VSPD kn":True, "WSPD mph":True, "Transit":True,
                  "% Channel Occupied":True, "Class":True,
                  "Course Behavior":True, "Yaw deg":True, "LOA ft":True,
                  "Beam ft":True, "Effective Beam ft":True, "Location":True,
                  "Date/Time UTC":True, "Name":False}
    fig = px.strip(df, x="Name", y="VSPD kn", color="Transit",
                   hover_data=hover_dict, hover_name="Name",
                   stripmode="overlay",
                   color_discrete_sequence=["#19336A", "green"],
                   width=900, height=600,
                   title= "<b>Vessel Speed Plot</b><br>" +
                           "One-way Transits: " +
                           str(round((df[df.loc[:,
                           ("Transit")] == "One-way Transit"]
                           .shape[0] / df.shape[0]) * 100, 2)) + "%<br>" +
                           "Two-way Transits: " +
                           str(round((df[df.loc[:,
                           ("Transit")] == "Two-way Transit"]
                           .shape[0] / df.shape[0]) * 100, 2)) + "%")
    fig.add_shape(type="line", x0=0, y0=10, x1=1, y1=10, xref="paper", yref="y",
                  line=dict(color="red", dash="solid", width=1.5))
    fig.update_layout(xaxis_title_text = "",
                      hoverlabel=dict(bgcolor="white", font_size=13),
                      legend_title_text="", width=875, height=650,
                      plot_bgcolor="#F1F1F1", font=dict(size=12),
                      titlefont=dict(size=14))
    fig.update_traces(marker_size=4)
    return fig
Ejemplo n.º 9
0
def plot_regression(mut_class):
    if mut_class.accuracy == None:
        plot_title = f'MSclassifier model prediction.'
    else:
        plot_title = f'MSclassifier model prediction. Model accuracy: {mut_class.accuracy}'
    accuracy = mut_class.accuracy
    # Plotting the regression prediction together with SVM margin maximizer
    plot = mut_class.data.sort_values(by='prediction')
    plot['counter'] = range(len(plot))

    fig = px.strip(plot,
                   y="prediction",
                   x='counter',
                   color='Sample type',
                   hover_data=['sample'])
    fig.update_traces(marker=dict(size=5))
    fig = fig.update_layout(title=plot_title,
                            xaxis_title="Samples",
                            yaxis_title="Prediction")

    fig = fig.add_trace(
        go.Scatter(x=[0, max(plot['counter'])],
                   y=[mut_class.model.margin, mut_class.model.margin],
                   name='Margin',
                   mode='lines',
                   line=dict(color='orange', width=3, dash='dash')))
    return fig
Ejemplo n.º 10
0
def plotStripPlot(df, groupBy, yStatCol, doMeanSem=True):
    dfMaster = df
    fig = px.strip(dfMaster,
                   x=groupBy,
                   color=groupBy,
                   y=yStatCol,
                   stripmode='overlay',
                   hover_data=dfMaster.columns)
    #
    return fig
Ejemplo n.º 11
0
def _create_fig_diffplot(
    ensdf: pd.DataFrame,
    colorby: str,
    vector_type: str,
    phase: str,
    boxmode: str,
    boxplot_points: str,
) -> Union[px.box, px.strip]:
    """Return boxplot or strip-plot fig"""

    all_columns = list(ensdf)  # column names

    prefix = "DIFF_W" if vector_type == "well" else "DIFF_G"
    phase_vector = {}
    phase_vector["Oil"] = prefix + "OPT"
    phase_vector["Water"] = prefix + "WPT"
    phase_vector["Gas"] = prefix + "GPT"

    facet_name = "DATE"
    if colorby == "DATE":
        facet_name = "ENSEMBLE"

    phase_columns = [x for x in all_columns if x.startswith(phase_vector[phase])]
    phase_well_labels = [col.split(":")[1] for col in phase_columns]
    text_labels = dict(value=f"{phase} diff (sim-obs)", variable="Well name")

    if boxplot_points == "strip":
        fig_phase = px.strip(
            ensdf,
            y=phase_columns,
            color=colorby,
            facet_col=facet_name,
            facet_col_wrap=2,
            labels=text_labels,
            stripmode=boxmode,
        )
    else:
        fig_phase = px.box(
            ensdf,
            y=phase_columns,
            color=colorby,
            facet_col=facet_name,
            facet_col_wrap=2,
            points=boxplot_points,
            labels=text_labels,
            boxmode=boxmode,
        )
    fig_phase.add_hline(0)
    fig_phase.update_xaxes(ticktext=phase_well_labels, tickvals=phase_columns)

    return fig_phase
Ejemplo n.º 12
0
def update_strip(location, scenario, attribute, num_scenarios, n):
    # arr = df[scenario+":"+attribute].to_numpy().astype(float)
    indexVals = random.sample(range(0, len(currentArr) - 1), 20)
    values = []

    for i in indexVals:
        values.append(currentArr[i])

    y = np.zeros(10)
    x = px.strip(y,
                 values,
                 orientation='h',
                 range_x=[currentArrMin, currentArrMax])
    return dcc.Graph(figure=x)
Ejemplo n.º 13
0
def main():
    """
    Runs the browser app to do data analysis.
    """
    df = pd.read_pickle(FILE_PATH)
    st.image(LOGO, format='PNG', use_column_width=True)
    st.title("ARC QC Analytics")
    st.markdown(WELCOME_MSG)

    articleno = st.sidebar.text_area("Article No. (enter on separate lines)",
                                     df['PH Mat. No.'].iloc[0])
    articleno = articleno.split('\n')
    df1 = df[df['PH Mat. No.'].isin(articleno)]
    charac = st.sidebar.selectbox("Characteristic", df1['Charac.'].unique())
    update = st.sidebar.button("Update Database")

    if update:
        pickle_data()

    new_df = df1[(df1['Charac.'] == charac)].copy()
    new_df = coerce_strings(new_df, 'Upper tolerance')
    new_df = coerce_strings(new_df, 'Lower tolerance')
    new_df = coerce_strings(new_df, 'Avg')
    new_df.loc[:,
               'Upper tolerance'] = new_df['Upper tolerance'].astype('float')
    new_df.loc[:,
               'Lower tolerance'] = new_df['Lower tolerance'].astype('float')
    new_df.loc[:, 'Avg'] = new_df['Avg'].astype('float')
    new_df = new_df.rename(columns={'Order:': 'Order'})

    st.header("Data")
    st.write(new_df[[
        'Order', 'PH Mat. No.', 'Charac.', 'Upper tolerance', 'Lower tolerance'
    ]])

    st.header("Chart")
    strip = px.strip(new_df,
                     x='Order',
                     y='Avg',
                     color='PH Mat. No.',
                     labels={
                         'Order': 'Order No.',
                         'Avg': charac,
                         'PH Mat. No.': 'Article Number'
                     })
    strip.update_layout(xaxis_type='category')
    st.plotly_chart(strip)

    st.header("Statistics")
    st.write(new_df.groupby('Order')['Avg'].describe())
Ejemplo n.º 14
0
def make_graphs(animal_chosen):
    # HISTOGRAM
    df_hist = df[df["animal_type"] == animal_chosen]
    fig_hist = px.histogram(df_hist, x="animal_breed")
    fig_hist.update_xaxes(categoryorder="total descending")

    # STRIP CHART
    fig_strip = px.strip(df_hist, x="animal_stay_days", y="intake_type")

    # SUNBURST
    df_sburst = df.dropna(subset=['chip_status'])
    df_sburst = df_sburst[df_sburst["intake_type"].isin(
        ["STRAY", "FOSTER", "OWNER SURRENDER"])]
    fig_sunburst = px.sunburst(
        df_sburst, path=["animal_type", "intake_type", "chip_status"])

    # Empirical Cumulative Distribution
    df_ecdf = df[df["animal_type"].isin(["DOG", "CAT"])]
    fig_ecdf = px.ecdf(df_ecdf, x="animal_stay_days", color="animal_type")

    # LINE CHART
    df_line = df.sort_values(by=["intake_time"], ascending=True)
    df_line = df_line.groupby(["intake_time",
                               "animal_type"]).size().reset_index(name="count")
    fig_line = px.line(df_line,
                       x="intake_time",
                       y="count",
                       color="animal_type",
                       markers=True)

    return [
        html.Div([
            html.Div([dcc.Graph(figure=fig_hist)], className="six columns"),
            html.Div([dcc.Graph(figure=fig_strip)], className="six columns"),
        ],
                 className="row"),
        html.H2("All Animals", style={"textAlign": "center"}),
        html.Hr(),
        html.Div([
            html.Div([dcc.Graph(figure=fig_sunburst)],
                     className="six columns"),
            html.Div([dcc.Graph(figure=fig_ecdf)], className="six columns"),
        ],
                 className="row"),
        html.Div([
            html.Div([dcc.Graph(figure=fig_line)], className="twelve columns"),
        ],
                 className="row"),
    ]
Ejemplo n.º 15
0
def plots():
    # sns.relplot(data=data, x='begin', y='A+', kind="line")
    # fig = px.scatter_matrix(data, )
    # fig = px.parallel_coordinates(data, color="A+", labels={"species_id": "A+", "sepal_width": "R-", },
    #                               color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2)
    fig = px.line(data, x='begin', y='A+')
    # sns.set_theme(style="ticks")
    # sns.pairplot(data)
    # plt.show()
    fig.show()
    fig = px.line(data, x='begin', y='R-')
    fig.show()

    fig = px.strip(data, x='A+', y='R-')
    fig.show()
def plotly_resp_by_state(df, columns, names, graphTitle):
    """ A function to plot the proportion of patients who gave each response to a survey question
    
    Arguments:
    columns = the name of the variable columns as a list of strings 
    names = the to-be names of the variable columns as a list of strings 
    graphTitle = title of the graph as a string
    
    Ouput: plotly plot"""
    
    #group by state
    grp_df=df.groupby(by='state').sum().reset_index()

    # create dict of current and to-be column names 
    name_dict={}

    for i, col in enumerate(columns):
        name_dict[col]=names[i]
    
    # add the following two columns to column list
    col_list=['state','number_of_completed_surveys']
    col_list.extend(columns)

    # create new df from grp_df and rename columns
    df=grp_df[col_list].rename(columns=name_dict)

    # change measure from count to proportion of total surveyed patients
    l=len(col_list)
    df.iloc[:,2:l]=df.values[:,2:l]/df.values[:,1,None]

    # restructure DataFrame
    df=df.melt(id_vars='state', value_vars=names, var_name='rating', value_name='proportion of patients')

    # create plot
    fig=px.strip(df, 
                 x='rating',
                 y='proportion of patients', 
                 orientation = "v", 
                 hover_data= ['state'])
    fig.update_layout(title_text=graphTitle, 
                      title_font_size=12, 
                      template="plotly_white", 
                      autosize=False,
                      width=400,
                      height=400)
    fig.update_yaxes(title_text="proportion of patients", title_font_size=12)
    fig.show()
Ejemplo n.º 17
0
def update_figure(selected_year):
    dot_fig = px.strip(
        prop_df,
        x=prop_df['funding_year'][prop_df['funding_year'] == selected_year],
        y=prop_df['property value'][prop_df['funding_year'] == selected_year],
        color=prop_df['BUILDING CLASS CATEGORY'][prop_df['funding_year'] ==
                                                 selected_year],
        labels={
            "x": "Funding Year",
            "y": "Property Value",
        },
        width=800,
        height=800)

    dot_fig.update_yaxes(matches=None)
    dot_fig.update_xaxes(matches=None)
    return dot_fig
Ejemplo n.º 18
0
def miner_dots(df):
    fig = px.strip(df,
                   x=df.index,
                   y="miner",
                   color="signal",
                   color_discrete_sequence=["red", "#2CA02C"])
    fig.update_layout(height=1000)
    fig.update_yaxes(categoryorder='total ascending',
                     showgrid=True,
                     tickson="boundaries",
                     title=None)
    fig.update_layout(title={
        'text': "Green Dot Good, Red Dot Bad (dots are blocks)",
        'x': 0.5
    })
    position_fig(fig, df)
    return fig
Ejemplo n.º 19
0
def build_distribuicao_cidades(path_data, grain):

    df = pd.read_csv(path_data + 'datasets/aggregations/df_class_munic.csv',
                     encoding='utf-8',
                     sep=';')
    # df.head()

    # Usuário seleciona o grão do eixo x
    mygrain = 'UF' if grain == 'by_uf' else 'Região'

    df = df.dropna()
    df = df.sort_values(by=mygrain)

    color_discrete_map = {
        'Impacto_Baixo': px.colors.diverging.Geyser[0],
        'Impacto_Médio': px.colors.diverging.Geyser[3],
        'Impacto_Alto': px.colors.diverging.Geyser[6]
    }

    fig = px.strip(
        df,
        y='Taxa_Letalidade',
        stripmode='overlay',
        x=mygrain,
        color='Impacto',
        color_discrete_map=color_discrete_map,
    )
    fig.add_scatter(x=df[mygrain],
                    y=df['Taxa_Letalidade_Br'],
                    mode='lines',
                    marker={'color': px.colors.diverging.Geyser[3]},
                    name='Letalidade Brasil')

    fig.update_layout(legend=dict(orientation="h",
                                  yanchor="bottom",
                                  y=1.02,
                                  xanchor="right",
                                  x=1),
                      legend_title_text='',
                      xaxis_title='',
                      yaxis_title='',
                      title='Letalidade por município')

    return fig
Ejemplo n.º 20
0
def update_figure(n_clicks, budget, cpc, ctl, ltc, clv):

    clv_expected=clv
    results_df =simulate(budget, cpc, ctl, ltc, clv)
    # fig=ff.create_distplot([results_df[c] for c in columns], columns)
    # fig = make_subplots(rows=3, cols=1)
    # fig.add_trace(ff.create_distplot([results_df['clv']],['CLVDist']),row=1,col=1)
    # fig.add_trace(ff.create_distplot([results_df['cpa']],['CPADist']),row=2,col=1)
    fig_clv=ff.create_distplot([results_df['clv']],['CLV'],colors=['rgb(0, 0, 100)'])
    fig_clv.update_layout(title_text='Customer Life Time Value')
    
    df=pd.concat([results_df['new_customer_count'],results_df['leads_count'],results_df['index']],axis=1).reset_index()
    df_melt=df.melt(id_vars='index', value_vars=['new_customer_count', 'leads_count'])
    fig_over_time=px.strip(df_melt, x='index' , y='value' , color='variable')
    fig_over_time.update_layout(title_text='Number of New Clients and Leads over each simulation')
    
    fig_cpa=ff.create_distplot([results_df['cpa']],['CPA'])
    fig_cpa.update_layout(title_text='Cost Per Acquisition')

    fig_cpl=ff.create_distplot([results_df['cpl']],['CPL'])
    fig_cpl.update_layout(title_text='Cost Per Lead')

    fig_new_customer=ff.create_distplot([results_df['new_customer_count']],['new customer count'],colors=['rgb(0, 200, 200)'])
    fig_new_customer.update_layout(title_text='New Customer Count')

    fig_clv_cpa=ff.create_distplot([results_df['clv - cpa']],['CLV - CPA'])
    fig_clv_cpa.update_layout(title_text='CLV - CPA')

    fig_campaign_ltv=ff.create_distplot([results_df['campaign_ltv']],['Campaign LTV'],colors=['magenta'])
    fig_campaign_ltv.update_layout(title_text='Campaign LTV')

    fig_campaign_return=ff.create_distplot([results_df['campaign_return']],['Campaign Return'])
    fig_campaign_return.update_layout(title_text='Campaign Return')

    mean_new_customer=round(results_df['new_customer_count'].mean())
    mean_cpa=round(results_df['cpa'].mean(),2)
    mean_cpl=round(results_df['cpl'].mean(),2)
    mean_diff=round(results_df['clv - cpa'].mean(),2)
    mean_ltv=round(results_df['campaign_ltv'].mean(),2)
    mean_return=round(results_df['campaign_return'].mean(),2)
    
    return fig_clv, fig_over_time, fig_cpa, fig_cpl, fig_clv_cpa, fig_new_customer,fig_campaign_ltv, fig_campaign_return, clv_expected, mean_cpa,mean_cpl ,mean_diff, mean_new_customer, mean_ltv, mean_return
Ejemplo n.º 21
0
def get_strip_plot(data):
    stripfig = px.strip(
        data_frame=data,
        x='variable',
        y='value',
        category_orders={"CLevel": ["low", "regular", "high"]},
        hover_data=['Method'],
        color='CLevel',
        color_discrete_map={"high": "firebrick", "regular": "goldenrod", "low": "cornflowerblue"},
        facet_col_spacing=0.5,
    )

    stripfig.update_traces(dict(marker_line_width=0.5, marker_line_color="grey"))
    stripfig.update_layout(
        height=500,
        margin=dict(l=0, r=0, t=0, b=0),
        template="plotly_white",
        font=dict(
            size=16,
        )
    )
    return stripfig
Ejemplo n.º 22
0
def test(mut_class):
    test_class = copy.deepcopy(mut_class.data)
    test_class = test_class[(test_class['training'] == 0)
                            & (test_class['class'] != 0)]
    X = np.asarray(test_class[mut_class.model.features])
    test_class['prediction'] = mut_class.model.classifier.predict(X)

    # Labeling samples according to their SVM binary classification as either proficient or defficient

    # We need to create svm_pred, a 2-d array with the nn prediction on the x axis and 0s on the y axis
    svm_pred = np.zeros((test_class.shape[0], 2))
    svm_pred[:, 0] = np.asarray(test_class['prediction'])

    # Then feed svm_pred into the trained SVM model and predict the outcome of each sample
    svm_pred = pd.DataFrame(mut_class.model.svm.predict(svm_pred))

    # Finally we label them in terms of proficiency or deficiency
    svm_pred = svm_pred.replace(-1, 'Proficient')
    svm_pred = svm_pred.replace(1, 'Deficient')

    # Append the prediction to the dataset
    test_class = test_class.reset_index()
    test_class['svm prediction'] = svm_pred

    #fig = px.scatter(test_class.data, y="prediction", x="Sample type",color='Sample type')

    fig = px.strip(test_class,
                   y="prediction",
                   x='class',
                   color='Sample type',
                   hover_data=['sample'])
    fig = fig.add_trace(
        go.Scatter(x=[-1.5, 1.5],
                   y=[mut_class.model.margin, mut_class.model.margin],
                   name='Margin',
                   mode='lines',
                   line=dict(color='orange', width=3, dash='dash')))
    fig.show()
Ejemplo n.º 23
0
def make_chart(chart_data):
    fig = px.strip(chart_data,
                   x="Programa",
                   y="Ano",
                   color="Categoria",
                   stripmode="overlay")

    title = {
        'text':
        f'Formação dos Docentes(Permanente e Colaboradores) ({", ".join(ANOS)})',
        'x': 0.5,
        'xanchor': 'center',
        'font': {
            'color': '#000000',
            'size': 20
        }
    }

    layout = go.Layout(title=title, font_size=15, height=1000, width=2500)

    fig.update_layout(layout)

    fig.show()
Ejemplo n.º 24
0
def plotRegion(meth):

    div_obj = ""
    valuesPlot = {}
    valuesPlot["methRatio"] = []
    valuesPlot["CpG ID"] = []

    for element in meth:
        idElement = element["chrom"] + "_" + element["start"]
        valueMeth = element["methRatio"]
        valuesPlot["methRatio"].append(valueMeth)
        valuesPlot["CpG ID"].append(idElement)

    df = pd.DataFrame(data=valuesPlot)

    fig = px.strip(df, 'CpG ID', 'methRatio', stripmode="overlay")

    # fig.update_layout(height=500,legend_orientation="h",xaxis_tickfont_size=14)
    # fig.update_xaxes(title_text='')
    # fig.update_yaxes(title_text='<b>Meth Ratio</b>',range=[-0.1, 1.1])
    div_obj = plot(fig, show_link=False, auto_open=False, output_type='div')

    return div_obj
Ejemplo n.º 25
0
def update_graph(task_value):
    dff = df[df['task'] == task_value]

    fig_fd = px.strip(dff, x=dff['ses'], y=dff['fd-per'])
    fig_fd_mean = px.strip(dff, x=dff['ses'], y=dff['fd-mean'])

    fig_dvars = px.strip(dff, x=dff['ses'], y=dff['dvars-per'])
    fig_dvars_mean = px.strip(dff, x=dff['ses'], y=dff['dvars-mean'])

    fig_std_dvars = px.strip(dff, x=dff['ses'], y=dff['std_dvars-per'])
    fig_std_dvars_mean = px.strip(dff, x=dff['ses'], y=dff['std_dvars-mean'])

    #fig = px.scatter(x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
    #                 y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
    #                 hover_name=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'])

    #fig.update_layout(margin={'l': 40, 'b': 40, 't': 10, 'r': 0}, hovermode='closest')

    return fig_fd, fig_fd_mean, fig_dvars, fig_dvars_mean, fig_std_dvars, fig_std_dvars_mean
Ejemplo n.º 26
0
stripfig = px.strip(
    data_frame=df,
    x='generation',
    y='suicides/100k pop',
    category_orders={
        "generation": [
            "G.I. Generation 1901-1927", "Silent 28'-45'", "Boomers 46'-64'",
            "Generation X 65'-80'", "Millenials 81'-96'",
            "Generation Z 96'-2012"
        ]
    },
    hover_data=['country'],  # values appear as extra data in the hover tooltip
    # color='sex',                 # differentiate color between marks
    # color_discrete_sequence=["springgreen","yellow"],             # set specific marker colors for discrete values
    # color_discrete_map={"male":"rosybrown" ,"female":"orangered"},  # map your chosen colors
    # orientation='v',             # 'v','h': orientation of the marks
    # stripmode='group',           # in 'overlay' mode, bars are top of one another.
    # in 'group' mode, bars are placed beside each other.
    #--------------------------------------------------------------------------------------------
    # facet_row='year',            # assign marks to subplots in the vertical direction
    # facet_col='year',            # assigns marks to subplots in the horizontal direction
    # facet_col_wrap=2,            # maximum number of subplot columns. Do not set facet_row!
    #--------------------------------------------------------------------------------------------

    # log_x=True,                  # x-axis is log-scaled
    # log_y=True,                  # y-axis is log-scaled
    # hover_name='country',        # values appear in bold in the hover tooltip
    # custom_data=['population'],  # values are extra data to be used in Dash callbacks

    # labels={"sex":"Gender",
    # "generation":"GENERATION"},  # map the labels
    # title='Suicide Rate',        # figure title
    # width=1000,                  # figure width in pixels
    # height=600,                  # igure height in pixels
    # template='seaborn',          # 'ggplot2', 'seaborn', 'simple_white', 'plotly',
    #                              # 'plotly_white', 'plotly_dark', 'presentation',
    #                              # 'xgridoff', 'ygridoff', 'gridon', 'none'

    # animation_frame='year',      # assign marks to animation frames
    # # animation_group='sex',     # use only when df has multiple rows with same object
    # # range_x=[5,50],            # set range of x-axis
    # range_y=[0,190],             # set range of x-axis
)
Ejemplo n.º 27
0
    histfunc="avg",
    color="smoker",
    barmode="group",
    facet_row="time",
    facet_col="day",
    category_orders={
        "day": ["Thur", "Fri", "Sat", "Sun"],
        "time": ["Lunch", "Dinner"]
    },
)
fig.write_html(os.path.join(dir_name, "histogram_histfunc.html"))

import plotly.express as px

tips = px.data.tips()
fig = px.strip(tips, x="total_bill", y="time", orientation="h", color="smoker")
fig.write_html(os.path.join(dir_name, "strip.html"))

import plotly.express as px

tips = px.data.tips()
fig = px.box(tips, x="day", y="total_bill", color="smoker", notched=True)
fig.write_html(os.path.join(dir_name, "box.html"))

import plotly.express as px

tips = px.data.tips()
fig = px.violin(
    tips,
    y="tip",
    x="smoker",
Ejemplo n.º 28
0
    def strip(x_data, y_data, f,color):
        df = pd.read_csv(settings.MEDIA_ROOT + '/' + f)
        fig = px.strip(df, x=x_data, y=y_data, color=color, animation_frame='Year', height=600)
        #fig.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)'})
        xbutton = []
        ybutton = []
        for col in df.columns:
            xbutton.append(
                dict(
                    args=['x', [df[str(col)]]],
                    label=str(col),
                    method='restyle'
                ),
            )
        for col in df.columns:
            ybutton.append(
                dict(
                    args=['y', [df[str(col)]]],
                    label=str(col),
                    method='restyle'
                ),
            )

        fig.update_layout(
            title="graph",
            yaxis_title="s",
            xaxis_title="activity",
            # Add dropdown
            updatemenus=[
                dict(
                    buttons=list([
                        dict(
                            args=["type", "line"],
                            label="Line",
                            method="restyle"
                        ),
                        dict(
                            args=["type", "bar"],
                            label="Bar",
                            method="restyle"
                        ),
                        dict(
                            args=["type", "pie"],
                            label="Pie",
                            method="restyle"
                        ),
                        dict(
                            args=["type", "violin"],
                            label="Violin",
                            method="restyle"
                        ),
                        dict(
                            args=["type", "box"],
                            label="Box",
                            method="restyle"
                        )
                    ]),
                    direction="down",
                    pad={"r": 10, "t": 10},
                    showactive=True,
                    x=0.1,
                    xanchor="left",
                    y=1.2,
                    yanchor="top"
                ),
                dict(
                    buttons=list(xbutton),
                    direction="down",
                    pad={"r": 10, "t": 10},
                    showactive=True,
                    x=0.250,
                    xanchor="left",
                    y=1.2,
                    yanchor="top"

                ),
                dict(
                    buttons=list(ybutton),
                    direction="down",
                    pad={"r": 10, "t": 10},
                    showactive=True,
                    x=0.4,
                    xanchor="left",
                    y=1.2,
                    yanchor="top"
                ),
            ],
            autosize=True,
            template="plotly_white"
        )
        plot_div = plot(fig, output_type='div', include_plotlyjs=True)
        return plot_div
import plotly.express as px

f = open("задание 14.txt", 'r', encoding="utf-8")
key_f = f.readline(-1).rstrip().split('\t')
df = {key_f[0]: [], key_f[1]: [], key_f[2]: [], key_f[3]: []}

for line in f:
    line_list = line.rstrip().split('\t')
    df['округ'].append(line_list[0])
    df['фамилия'].append(line_list[1])
    df['предмет'].append(line_list[2])
    df['балл'].append(int(line_list[3]))
# print(df)
f.close()

fig = px.strip(df,
               x='округ',
               y='балл',
               color="предмет",
               template='presentation')
fig.show()
Ejemplo n.º 30
0
fig.update_traces(diagonal_visible=False)
plot(fig)

# these 3 variables have the strongest separation for the target
group = [
    "RepublicanFraction Ohio", "RepublicanFraction Wyoming",
    "RepublicanFraction Idaho"
]

# plot the group of 3 variables across categories
fig = px.scatter_3d(df,
                    x=group[0],
                    y=group[1],
                    z=group[2],
                    color=" DemocratWon",
                    opacity=0.7)
plot(fig)

# plot two variables across categories
fig = px.density_contour(df,
                         x=group[0],
                         y=group[1],
                         marginal_x="histogram",
                         marginal_y="box",
                         color=" DemocratWon")
plot(fig)

# plot SalePrice across categories
fig = px.strip(df, y=group[0], color=" DemocratWon")
plot(fig)