示例#1
0
        def update_pc(clickData, rangeData, n):
            if self.pc_data.empty:
                return go.Figure(data=[go.Scatter(x=[], y=[])])
            trigger_context = dash.callback_context.triggered[0]['prop_id']
            if len(dash.callback_context.triggered) <= 1 and self.update_available == False and (trigger_context == 'interval-component2.n_intervals'):
                raise PreventUpdate

            pc_data_copy = self.pc_data

            if len(clickData) == 0:
                if self.update_available:
                    pc = px.parallel_coordinates(pc_data_copy.apply(make_ints, axis=1), color="accuracy", dimensions=self.hierarchy_path + ['accuracy'],
                                    color_continuous_scale='RdBu', height=350)
                    return pc
                raise PreventUpdate

            # delete entries
            pc_data_copy = pc_data_copy.query("accuracy >= " + str(rangeData[0]) + " and accuracy <= " + str(rangeData[1]))

            if isinstance(clickData, list):
                clickData = clickData[0]

            if 'recommendationval' in clickData:
                raise PreventUpdate

            if clickData.split("/")[:-2] == []:
                pc = px.parallel_coordinates(pc_data_copy.apply(make_ints, axis=1), color="accuracy", dimensions=self.hierarchy_path + ['accuracy'],
                                    color_continuous_scale='RdBu', height=350)
                return pc
            if clickData:
                click_path = clickData.split("/")[:-1][1:]
                subset_counter = len(click_path)
                if click_path == []:
                    return pc_o

                selected_df = pc_data_copy
                j = -1
                for i in click_path:
                    j+=1
                    if "=" in i:
                        comps_name = i.split("=")
                        hyp_name = comps_name[0]
                        hyp_val = comps_name[1]
                        selected_df = selected_df[selected_df.apply(lambda x: x['model_params'][hyp_name] == hyp_val if hyp_name in x['model_params'] else False, axis=1)]
                    else:
                        selected_df = selected_df[selected_df['model'] == i]
                sample_vals = selected_df.iloc[0]
                labels_pc = {}
                for i in self.hierarchy_path[subset_counter:]:
                    if sample_vals[i]:
                        labels_pc[i] = sample_vals[i].split("=")[0]

                selected_df = selected_df.apply(make_ints, axis=1)
                self.pc = px.parallel_coordinates(selected_df, color="accuracy", dimensions=self.hierarchy_path[subset_counter:] + ['accuracy'],
                                        labels=labels_pc, color_continuous_scale='RdBu', height=350)

                return self.pc
            self.pc = px.parallel_coordinates(pc_data_copy.apply(make_ints, axis=1), color="accuracy", dimensions=self.hierarchy_path + ['accuracy'],
                                    color_continuous_scale='RdBu', height=350)
            return self.pc
def setScatter(click,selection,stories):
    global pcd_set,orderd_axes,pcdFig,scatter,x,y,bar1,bar2,orig_df
    ctx = dash.callback_context
    trigger = ctx.triggered[0]['prop_id']
    if trigger == 'CorrMat.clickData':
        x = click['points'][0]['x'] if click != None else x
        y = click['points'][0]['y'] if click != None else y
        bar1 = barUpdate(x)
        bar2 = barUpdate(y)
        if x != None:
            scatter =  px.scatter(orig_df,x=x,y=y,title="The Effect of " + x + " on " + y)
            scatter.update_traces(selectedpoints=None, mode='markers', marker={ 'color': "red"}, unselected={'marker': {'color':px.colors.sequential.Blugrn[4]}})
            scatter.update_layout(dragmode='select',xaxis_showgrid=False, yaxis_showgrid=False)
            scatter.update_xaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
            scatter.update_yaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
            scatter.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)','paper_bgcolor': 'rgba(0, 0, 0, 0)'})
        return scatter,bar1,bar2,defaults['PCD']
    elif trigger == 'Scatter.selectedData':
        selectedpoints = df.index
        if selection != None:
            selectedpoints = np.intersect1d(selectedpoints,[p['pointNumber'] for p in selection['points']])
            if len(selectedpoints) > 0:
                newFig = px.parallel_coordinates(pcd_set.iloc[selectedpoints],dimensions = ordered_axes,color_continuous_scale=[px.colors.sequential.Blugrn[4]])
                scatter = px.scatter(orig_df,x=x,y=y,title="The Effect of " + x + " on " + y,color_discrete_sequence=[px.colors.sequential.Blugrn[4]])
                scatter.update_traces(selectedpoints=selectedpoints, mode='markers', marker={ 'color': "red"}, unselected={'marker': {'color':px.colors.sequential.Blugrn[4]}})
                scatter.update_layout(dragmode='select',xaxis_showgrid=False, yaxis_showgrid=False)
                scatter.update_xaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
                scatter.update_yaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
                scatter.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)','paper_bgcolor': 'rgba(0, 0, 0, 0)'})
                return scatter,bar1,bar2,newFig
            else:
                return scatter,bar1,bar2,pcdFig
        else: 
            return scatter,bar1,bar2,pcdFig
    else:
        if stories == None:
            return defaults['scatter'],defaults['bar1'],defaults['bar2'],defaults['PCD']
        else:
            if stories == 1:
                x = "G1"
                y = "G3"
                selectedpts = [8,15,31,47,51,56,57,59,60,65,69,87,101,104,109,113,115,116,135, 151, 181, 183, 185, 196, 238, 240, 243, 250, 265, 266, 267, 276, 296, 300, 303, 306,312, 314, 316, 327, 332, 335, 336, 337, 338,343, 344, 348, 349, 356, 359, 365, 374, 378,381, 386, 387, 396, 400, 416, 427, 448, 450, 499, 509, 510, 525, 549, 594, 595, 596, 606,615, 617, 618, 620, 623, 630, 634, 636, 645]
            else:
                x = "studytime"
                y = "failures"
                selectedpts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 164, 165, 166, 167, 168, 171, 172, 174, 176, 177, 178, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 280, 281, 282, 283, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 408, 409, 410, 411, 412, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 479, 480, 481, 482, 483, 484, 485, 486, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 544, 545, 546, 547, 548, 549, 550, 551, 553, 554, 555, 556, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 570, 573, 574, 575, 576, 577, 578, 579, 580, 582, 583, 584, 585, 586, 587, 588, 589, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648]
            newFig = px.parallel_coordinates(pcd_set.iloc[selectedpts],dimensions = ordered_axes,color_continuous_scale=[px.colors.sequential.Blugrn[4]])
            scatter = px.scatter(orig_df,x=x,y=y,title="The Effect of " + x + " on " + y,color_discrete_sequence=[px.colors.sequential.Blugrn[4]])
            scatter.update_traces(selectedpoints=selectedpts, mode='markers', marker={ 'color': "red"}, unselected={'marker': {'color':px.colors.sequential.Blugrn[4]}})
            scatter.update_layout(dragmode='select',xaxis_showgrid=False, yaxis_showgrid=False)
            scatter.update_xaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
            scatter.update_yaxes(showline=True, linewidth=2, linecolor='black',zeroline=False)
            scatter.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)','paper_bgcolor': 'rgba(0, 0, 0, 0)'})
            bar1 = barUpdate(x)
            bar2 = barUpdate(y)
            return scatter,bar1,bar2,newFig
示例#3
0
def plot_data(df_poll):
    fig = px.parallel_coordinates(df_poll)
    plot(fig)
    #fig = px.parallel_categories(df)
    #plot(fig)

    return
def plot_variables():
    for yr in [2005, 2008, 2012]:
        df = pd.DataFrame()
        for file in glob.glob(config.EA_experiment_output_dir + "/**/VAR*.tsv", recursive=True):
            if re.match(r'.*RecSys-RS-yr_' + str(yr) + '.*', file):
                problem = re.findall(r'RecSys[^/]*', file)[0]
                algo = re.search(r'(GDE3)|(NSGAIII)|(SPEA2)', file).group()
                temp_df = pd.read_csv(file, sep='\s+', header=None)
                temp_df['algo'] = algo
                temp_df['problem'] = problem
                temp_df['col_value'] = np.random.uniform(0, 1, size=temp_df.shape[0])
                df = df.append(temp_df)
        df.columns = ["CF-user_rec", "CF-user_artist", "Tailored", 'algo', 'problem', 'col_value']
        df['sum'] = df[["CF-user_rec", "CF-user_artist", "Tailored"]].sum(axis=1)
        for colname in ["CF-user_rec", "CF-user_artist", "Tailored"]:
            df[colname] = df[colname] / (df['sum'] + 1e-6)
        # print(df)
        fig = px.parallel_coordinates(df, color="col_value", dimensions=["CF-user_rec", "CF-user_artist", "Tailored"],
                                      color_continuous_scale=px.colors.qualitative.Set1, )
        fig.update(layout_coloraxis_showscale=False)
        fig.write_image(f"../images/front_variables/front_var_yr_{yr}.pdf")

        df = df.rename(columns={"CF-user_rec": 'CF-user-rec', "CF-user_artist": "CF-user-artist"})

        fig = plt.figure(figsize=(8, 6))
        pd.plotting.parallel_coordinates(df, "algo",
                                         cols=["CF-user-rec", "CF-user-artist", "Tailored"],
                                         color=["lime", "tomato", "dodgerblue"],
                                         alpha=0.2,
                                         axvlines_kwds={"color": "black"})
        plt.autoscale()
        plt.legend(facecolor='white', framealpha=0.9)
        plt.savefig(f"../images/front_variables/front_var_yr_{yr}.svg")
def parallel_plots(type_plot):
    label_data['Solar (sq-m)'] = label_data['Solar Area (m^2)']
    label_data['Swept (sq-m)'] = label_data['Swept Area (m^2)']
    label_data['Emissions (kg)'] = label_data['Emission (kg CO2)']
    label_data['Battery (kW)'] = label_data['Battery Capacity (kW)']
    label_data['CHP (kW)'] = label_data['CHP Electricty Capacity (kW)']
    label_data['Boilers (kW)'] = label_data['Boilers Capacity (kW)']

    if type_plot == 'cost':
        #cols = ['Solar Area (sq-m)', 'Swept Area (sq-m)', 'Boilers Capacity (kW)', 'CHP Electricty Capacity (kW)', 'Battery Capacity (kW)','Emission (kg CO2)','Cost ($)']
        cols = [
            'CHP (kW)', 'Boilers (kW)', 'Solar (sq-m)', 'Swept (sq-m)',
            'Battery (kW)', 'Emissions (kg)', 'Cost ($)'
        ]
        color_plot = px.colors.sequential.Blues
    if type_plot == 'emissions':
        cols = [
            'CHP (kW)', 'Boilers (kW)', 'Solar (sq-m)', 'Swept (sq-m)',
            'Battery (kW)', 'Cost ($)', 'Emissions (kg)'
        ]
        color_plot = px.colors.sequential.Reds
    fig_new = px.parallel_coordinates(label_data,
                                      color=cols[-1],
                                      dimensions=cols,
                                      color_continuous_scale=color_plot)
    fig_new.update_layout(font=dict(size=18, ))
    fig_new.write_image(os.path.join(
        results_path, 'Parallel_coordinates_' + type_plot + '.png'),
                        width=980,
                        height=450,
                        scale=3)
示例#6
0
def update_parallel_coordinates(selectedData):
    country_codes = []
    if not selectedData:
        country_codes = ['USA']
    else:
        for point in selectedData['points']:
            country_codes.append(point['location'])

    df_new = df
    df_new['date'] = pd.to_datetime(df['date'])
    df_new = df_new[(df_new['iso_code'].isin(country_codes))
                    & (df_new['date'] > dt(2020, 4, 1)) &
                    (df_new['date'] < dt(2020, 11, 1))]
    df_new = df_new[[
        'total_cases', 'total_deaths', 'positive_rate', 'new_tests',
        'covid_tweet_count', 'new_cases', 'stringency_index', 'new_deaths'
    ]]
    fig = px.parallel_coordinates(df_new,
                                  color='new_cases',
                                  dimensions=df_new.columns)
    fig.update_traces(labelfont=dict(color='#ccff00', size=14),
                      tickfont=dict(color='#ccff00', size=14))
    fig.update_layout(
        plot_bgcolor='#383838',
        paper_bgcolor='#383838',
    )
    fig.update_layout(margin={"r": 30, "t": 60, "l": 50, "b": 50})
    return fig
def analyze_hyperparameters(data,
                            score_col,
                            hyperparameters=[],
                            log_scale_vars=[]):

    float_hyperparams = list(data.dtypes.index[data.dtypes == 'float'])

    if not hyperparameters:
        hyperparameters = data.columns.drop(score_col, axis=1)

    for col in hyperparameters:
        if col in float_hyperparams:
            if col in log_scale_vars:
                plt.xscale('log')
            ax = sns.lineplot(x=col, y=score_col, data=data)
            ax.set(title=f"{col} vs {score_col}")
            plt.show()
        else:
            ax = sns.boxenplot(x=col, y=score_col, data=data)
            ax.set(title=f"{col} vs {score_col}")
            plt.show()

    fig = px.parallel_coordinates(
        data[hyperparameters + [score_col]],
        color="f1_val",
        color_continuous_scale=px.colors.diverging.RdYlGn)
    fig.show()
示例#8
0
def display_parallel():
    figure = None
    df2 = df[[
        "age", "pop", "pov", "college", "urate", "county_income", "h_income",
        "share_white", "share_black", "share_hispanic"
    ]]
    correlated_data = df2.corr(method='pearson').abs().sum(axis=0).sort_values(
        ascending=False, inplace=False)
    A1 = correlated_data[0]
    correlated_data = df2.corr(method='pearson')
    df3 = df2[[
        "pov", "h_income", "college", "urate", 'share_black', 'share_white',
        'share_hispanic', 'age', 'pop', 'county_income'
    ]]
    figure = px.parallel_coordinates(df3,
                                     title="Parallel Coordinates",
                                     height=500,
                                     color_continuous_scale=None,
                                     range_color=[1, 2],
                                     color_continuous_midpoint=2,
                                     labels={
                                         "pov": "Poverty Rate",
                                         "h_income": "House Hold Income",
                                         "college": "College Rate",
                                         "urate": "Unemployment Rate",
                                         "share_black": "Black Population",
                                         "share_white": "White Population",
                                         "share_hispanic":
                                         "Hispanic Population",
                                         "age": "Age",
                                         "pop": "Population",
                                         "county_income": "County Income"
                                     })
    return figure
示例#9
0
def parallel_coordinates():
    """Parallel Coordinates Plot."""

    # YOUR CODE HERE!
    avg = df.groupby([df['neighborhood']]).mean()
    parallel_plot = px.parallel_coordinates(avg, color='sale_price_sqr_foot')
    return parallel_plot
示例#10
0
def plot_parallel_coordinates(
    plotter: Plotter,
    mcmc_tables: List[pd.DataFrame],
    mcmc_params: List[pd.DataFrame],
):
    parameters = [
        param for param in mcmc_params[0].loc[:, "name"].unique().tolist()
        if "dispersion_param" not in param
    ]

    target_n_lines = 500.0
    n_samples = int(target_n_lines / len(mcmc_tables))
    combined_mcmc_df = merge_and_pivot_mcmc_parameters_loglike(
        mcmc_tables, mcmc_params, parameters, n_samples_per_chain=n_samples)
    w = len(parameters) * 200
    h = 800
    labels = {}
    for param in parameters:
        labels[param] = get_plot_text_dict(param)
    figure = px.parallel_coordinates(
        combined_mcmc_df,
        color="fitness",
        dimensions=parameters,
        labels=labels,
        color_continuous_scale=px.colors.diverging.Tealrose,
        height=h,
        width=w,
    )
    figure.show()
示例#11
0
def main(args):
    omit_hue = False
    df = pd.read_csv("./data.csv", sep=",")

    selected_attributes = args.attributes or list(df.columns)

    selected_attributes = [
        attribute.upper() for attribute in selected_attributes
    ]
    if args.hue.upper() not in selected_attributes:
        omit_hue = True
        selected_attributes.append(args.hue.upper())

    selected_start = args.start if args.start and args.start >= 0 and args.start < len(
        df.index) else 0
    selected_end = args.end if args.end and args.end < len(df.index) else len(
        df.index)

    if args.ascending:
        df = df.sort_values(by=args.ascending.upper(), ascending=True)
    if args.descending:
        df = df.sort_values(by=args.descending.upper(), ascending=False)

    df = df[selected_attributes].iloc[selected_start:selected_end]

    if omit_hue:
        selected_attributes.remove(args.hue.upper())

    fig = px.parallel_coordinates(df,
                                  dimensions=selected_attributes,
                                  color=args.hue.upper())
    fig.show()
示例#12
0
def plot_parallel_coords(results_df: pd.DataFrame):

    import plotly.express as px

    cols_keep = [col for col in results_df if "param_" in col]
    cols_keep += ["mean_test_score"]

    results_df = results_df[cols_keep]
    # want to convert object columns to type float
    results_df = results_df.apply(pd.to_numeric,
                                  errors="ignore",
                                  downcast="float")

    fig = px.parallel_coordinates(
        results_df,
        color="mean_test_score",
        labels=dict(
            zip(
                list(results_df.columns),
                list(["_".join(i.split("_")[1:]) for i in results_df.columns]),
            )),
        color_continuous_scale=px.colors.diverging.Earth,
        # color_continuous_midpoint=27,
    )

    fig.show()
示例#13
0
def plot_sim_par_coords(panda_frame, savedir=None):
    # Generates a parallel coordinate system and saves to html file
    fig = px.parallel_coordinates(panda_frame, color="VISno")
    if savedir == None:
        fig.show()
    else:
        fig.write_html(savedir + "/parrallel_coordinates_plot.html")
示例#14
0
def parallel(df):
    """

    :param df:
    :return:
    """
    return go.Figure(px.parallel_coordinates(df, color='Species'))
示例#15
0
def make_parallel_coordinates(c_df):
    figure = px.parallel_coordinates(c_df,
                                     dimensions=[
                                         'Global_Sales', 'NA_Sales',
                                         'EU_Sales', 'Other_Sales', 'Rank',
                                         'JP_Sales', 'Year'
                                     ],
                                     color='Rank',
                                     title='Parallel Coordinates Display',
                                     labels={
                                         "Global_Sales":
                                         "Global Sales (Millions)",
                                         "EU_Sales": "Europe Sales (Millions)",
                                         "NA_Sales":
                                         "North America Sales (Millions)",
                                         "Other_Sales":
                                         "Other Countries Sales (Millions)",
                                         "Rank": "Rank",
                                         "JP_Sales": "Japan Sales (Millions)",
                                         "Year": "Year"
                                     })
    figure.update_layout(
        title_x=0.5,
        margin=dict(b=10),
        height=275,
    )
    return figure
示例#16
0
    def plotly(self, progress_data, search_id):
        if progress_data is None or len(progress_data) <= 1:
            return None

        filter_df = self.search_id_dict[search_id]["filt_f"]

        progress_data = progress_data.drop(
            ["nth_iter", "score_best", "nth_process", "best"], axis=1
        )

        if filter_df is not None:
            progress_data = self.filter_data(progress_data, filter_df)

        # remove score
        prog_data_columns = list(progress_data.columns)
        prog_data_columns.remove("score")

        fig = px.parallel_coordinates(
            progress_data,
            dimensions=prog_data_columns,
            color="score",
            color_continuous_scale=color_scale,
        )
        fig.update_layout(width=1200, height=540)

        return fig
示例#17
0
def do_plot(csv_filename):
    summary = pd.read_csv(csv_filename)

    # the regular hmm-generated:
    if csv_filename == 'summary.csv' or csv_filename == 'hmm-summary.csv':
        selection = summary[['N', 'M', 'I', 'Test avgAc']]

    # ad hoc for other tests:
    elif csv_filename == 'nb-summary.csv':
        selection = summary[['M', 'Train avgAc', 'Test avgAc']]

    elif csv_filename == 'mm-summary.csv':
        selection = summary[['M', 'Train avgAc', 'Test avgAc']]

    else:
        print(f'unrecognized file: {csv_filename}')
        return

    fig = px.parallel_coordinates(selection,
                                  color='Test avgAc',
                                  color_continuous_scale=px.colors.diverging.Picnic
                                  )

    # fig.write_image('summary-parallel.png')
    fig.show()
示例#18
0
    def get_parallel_plot(self) -> go.Figure:
        """Returns a Figure containing the parallel plot of
        clusters' centroids.
        """

        fig = px.parallel_coordinates(self.graph.centroids,
                                      color=self.graph.centroids.index,
                                      dimensions=self.graph.centroids.columns)
        return fig
def parallel_coordinates_plotly(*args,
                                plotly_width=1200,
                                plotly_height=600,
                                **kwargs):
    fig = px.parallel_coordinates(*args,
                                  **kwargs,
                                  color_continuous_scale=color_scale)
    fig.update_layout(autosize=False, width=plotly_width, height=plotly_height)

    return fig
示例#20
0
def plot_grid_result(df, color, title, viz):
    fig = parallel_coordinates(df,
                               color=color,
                               title=title,
                               width=2 * REF_WIDTH,
                               height=2 * REF_HEIGHT)
    viz.plotlyplot(fig,
                   opts={
                       'width': 2 * REF_WIDTH,
                       'height': 2 * REF_HEIGHT
                   })
示例#21
0
def generate_parallel(df):
    fig = px.parallel_coordinates(
        df,
        labels={
            "sepal_width": "Sepal Width",
            "sepal_length": "Sepal Length",
            "petal_width": "Petal Width",
            "petal_length": "Petal Length",
        },
    )
    return fig
示例#22
0
def parrallel_plot(df):
    pp_df = pd.DataFrame(
        df, columns=['status_reco', 'Price', 'Nb_language', 'Nb_achievements'])

    pp_df = pp_df.drop(pp_df[pp_df.Price > 300].index)
    pp_df = pp_df.drop(pp_df[pp_df.Nb_achievements > 6000].index)
    fig = px.parallel_coordinates(pp_df,
                                  color="status_reco",
                                  color_continuous_scale="Inferno",
                                  color_continuous_midpoint=2)
    return fig
示例#23
0
def display_parallel_coordinates_centroids(df, num_clusters):
    '''Display a parallel coordinates plot for the centroids in df'''

    # Draw the chart
    pc = px.parallel_coordinates(data_frame=df, color='predicted_cluster')
    pio.renderers.default = 'browser'
    pc.show()

    # Stagger the axes
    ax = plt.gca()
    for tick in ax.xaxis.get_major_ticks()[1::2]:
        tick.set_pad(20)
示例#24
0
def show_points_parallel(nanotubes_df):
    st.subheader('Данные по нанотрубкам в параллельных координатах')
    fig = px.parallel_coordinates(
        nanotubes_df, color='Толщина кольца, нм',
        dimensions=['Диаметр (внутренний), нм', 'Температура синтеза, C',
                    'Расход аргона, мл/мин', 'Скорость роста кольца, нм/мин',
                    'Время синтеза, мин', 'Расход смеси этанол/вода, мл/мин'],
        color_continuous_scale=px.colors.diverging.Tealrose,
        color_continuous_midpoint=7)
    fig.update_layout(
        # autosize=False,
        height=700)
    st.plotly_chart(fig, use_container_width=True)
示例#25
0
def display_parallel_coordinates(df, num_clusters):
    '''Display a parallel coordinates plot for the clusters in df'''

    # Select data points for individual clusters
    cluster_points = []
    for i in range(num_clusters):
        cluster_points.append(df[df.predicted_cluster == i])

    # Draw the chart
    pc = px.parallel_coordinates(data_frame=df, color='predicted_cluster')
    pio.renderers.default = 'browser'
    pc.show()

    # Stagger the axes
    ax = plt.gca()
    for tick in ax.xaxis.get_major_ticks()[1::2]:
        tick.set_pad(20)
示例#26
0
def get_weater_pc(rule_tids: list,
                  tid_weather: pd.DataFrame) -> px.parallel_coordinates:
    '''
    :param rule_tids: turnaround ids associated with rules
    :param tid_weather: weather dataframe with weather info and turnaround ids
    :return: parallel coordinates of median weather condition
    '''
    data = []
    for tids in rule_tids:
        data.append(tid_weather[tid_weather['Turnaround ID'].isin(
            tids)].median().to_dict())
    fig = px.parallel_coordinates(
        data, title='<b>Median Weather Condition per Pattern</b>', height=200)
    fig.update_layout(margin=dict(l=20, r=20, b=20, pad=0, t=80),
                      font=dict(size=10),
                      titlefont={'size': 11})
    return fig
示例#27
0
def plot_parallel_coordinates(data, color, fileName):

    fig = px.parallel_coordinates(
        data, color=color, color_continuous_scale=px.colors.diverging.Tealrose)
    fig.update_layout(
        autosize=False,
        width=width_plotly,
        height=height_plotly,
        #title=go.layout.Title(text="Parallel coordinate plot of dataset"),
        #xaxis=dict(title=xlabel, range=[-0.1,10]),
        #yaxis=dict(title=ylabel, range=[-0.1,10]),
        font=dict(family="Palatino", color="Black", size=12),
    )

    fig.write_image(str(Path(__file__).resolve().parents[2] / \
                                "reports" / "figures"
                                / Path(fileName)))
    fig.show()
示例#28
0
def generate_parallel_coordinates_plot(df):

    df = df.drop('obs', 1)
    fig = px.parallel_coordinates(
        df,
        color="positivo",
        labels={
            "preg": "qtd. gravidez",
            "plas": "Plasma",
            "pres": "Pressão",
            "skin": "Prega cutânea",
            "test": "Insulina",
            "mass": "IMC",
            "pedi": "dbf",
            "age": "idade"
        },
        color_continuous_scale=px.colors.diverging.Tealrose)
    st.plotly_chart(fig, use_container_width=True)
示例#29
0
def par_plot(df):
    dimensions = [
        col
        for col in df.columns
        if col
        not in [
            "year",
            "broad_impact",
        ]
    ]
    fig = px.parallel_coordinates(
        df,
        color="world_rank",
        dimensions=dimensions,
        color_continuous_scale=px.colors.diverging.Tealrose,
        color_continuous_midpoint=50,
    )
    return fig
示例#30
0
def plot_parallel_coordinates_plotly(
        experiment: Experiment,
        ignored_names: Optional[List[str]] = None) -> go.Figure:
    """Plot trials as a parallel coordinates graph

    Args:
        experiment: Experiment containing trials to plot
        ignored_names: Metrics present in the experiment data we wish to exclude from
            the final plot. By default we ignore ["generation_method", "trial_status",
            "arm_name"]

    Returns:
        go.Figure: parellel coordinates plot of all experiment trials
    """
    df = prepare_experiment_for_plotting(experiment=experiment,
                                         ignored_names=ignored_names)

    return px.parallel_coordinates(df, color=df.columns[0])