Python seaborn.lmplot() Examples

The following are 10 code examples of seaborn.lmplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module seaborn , or try the search function .
Example #1
Source File: noisy_observations.py    From adversarial-policies with MIT License 6 votes vote down vote up
def noisy_adversary_opponent_subset_plot(
    original_df, subset_specs, transform_specs, logistic=True, plot_line=True, savefile=None
):
    subset_df = subset(original_df, subset_specs)
    if len(subset_df) == 0:
        return
    transformed_df = transform(subset_df, transform_specs)
    plt.figure(figsize=(10, 7))
    if plot_line:
        sns.lmplot(data=transformed_df, x="log_noise", y="agent0_win_perc", logistic=logistic)
    else:
        sns.scatterplot(data=transformed_df, x="log_noise", y="agent0_win_perc")
    plt.title(
        "{}: Noisy Zoo{} Observations vs Adversary".format(
            subset_specs["env"], subset_specs["agent0_path"]
        )
    )
    if savefile is not None:
        plt.savefig(savefile)
    else:
        plt.show()
    plt.close() 
Example #2
Source File: noisy_observations.py    From adversarial-policies with MIT License 6 votes vote down vote up
def noisy_multiple_opponent_subset_plot(
    original_df, subset_specs, transform_specs, logistic=True, savefile=None
):
    subset_df = subset(original_df, subset_specs)
    if len(subset_df) == 0:
        return
    transformed_df = transform(subset_df, transform_specs)
    plt.figure(figsize=(10, 7))
    sns.lmplot(
        data=transformed_df,
        x="log_noise",
        y="agent0_win_perc",
        hue="agent1_path",
        logistic=logistic,
    )
    plt.title(
        "{}: Noisy Zoo{} Observations vs Normal Zoos".format(
            subset_specs["env"], subset_specs["agent0_path"]
        )
    )
    if savefile is not None:
        plt.savefig(savefile)
    else:
        plt.show()
    plt.close() 
Example #3
Source File: atlas3.py    From ssbio with MIT License 6 votes vote down vote up
def make_biplot(self, pc_x=1, pc_y=2, outpath=None, dpi=150, custom_markers=None, custom_order=None):
        if not custom_order:
            custom_order = sorted(self.observations_df[self.observation_colname].unique().tolist())
        if not custom_markers:
            custom_markers = self.markers
        plot = sns.lmplot(data=self.principal_observations_df,
                              x=self.principal_observations_df.columns[pc_x - 1],
                              y=self.principal_observations_df.columns[pc_y - 1],
                              hue=self.observation_colname,
                              hue_order=custom_order,
                              fit_reg=False,
                              size=6,
                              markers=custom_markers,
                            scatter_kws={'alpha': 0.5})
        plot = (plot.set(title='PC{} vs. PC{}'.format(pc_x, pc_y)))
        if outpath:
            plot.savefig(outpath, dpi=dpi)
        else:
            plt.show()
        plt.close() 
Example #4
Source File: plotting.py    From nltools with MIT License 6 votes vote down vote up
def scatterplot(stats_output):
    """ Plot Prediction Scatterplot

    Args:
        stats_output: a pandas file with prediction output

    Returns:
        fig: Will return a seaborn scatterplot

    """

    if "yfit_xval" in stats_output.columns:
        sns.lmplot("Y", "yfit_xval", data=stats_output)
    else:
        sns.lmplot("Y", "yfit_all", data=stats_output)
    plt.xlabel("Y", fontsize=16)
    plt.ylabel("Predicted Value", fontsize=16)
    plt.title("Prediction", fontsize=18)
    return 
Example #5
Source File: PCA.py    From pySPM with Apache License 2.0 6 votes vote down vote up
def pca_scatter(self, classifs=None, light=False):
        import seaborn as sns
        foo = self.get_pca_transf()
        if classifs is None:
            if light:
                plt.scatter(foo[:, 0], foo[:, 1])
            else:
                bar = pd.DataFrame(
                    list(zip(foo[:, 0], foo[:, 1])), columns=["PC1", "PC2"])
                sns.lmplot("PC1", "PC2", bar, fit_reg=False)
        else:
            if light:
                plt.scatter(foo[:, 0], foo[:, 1], color=cm.Scalar)
            else:
                bar = pd.DataFrame(list(zip(foo[:, 0], foo[:, 1], classifs)), columns=[
                                   "PC1", "PC2", "Class"])
                sns.lmplot("PC1", "PC2", bar, hue="Class", fit_reg=False) 
Example #6
Source File: tech-report-2016.py    From pylangacq with MIT License 6 votes vote down vote up
def visualize_can_eng_MLUw(child_name, can_reader, eng_reader, legend=True):
    x_label = '{}\'s age in months'.format(child_name)
    
    can_filenames = can_reader.filenames(sorted_by_age=True)
    can_ages = can_reader.age(months=True)
    can_MLUs = can_reader.MLUw()
    
    eng_filenames = eng_reader.filenames(sorted_by_age=True)
    eng_ages = eng_reader.age(months=True)
    eng_MLUs = eng_reader.MLUw()
    
    df = pd.DataFrame({x_label: [can_ages[fn] for fn in can_filenames] + [eng_ages[fn] for fn in eng_filenames],
                       'MLUw': [can_MLUs[fn] for fn in can_filenames] + [eng_MLUs[fn] for fn in eng_filenames],
                       'Language': ['Cantonese']*len(can_reader) + ['English']*len(eng_reader)})
    
    MLU_plot = sns.lmplot(x=x_label, y='MLUw', hue='Language', data=df, markers=['o', 'x'],
                          legend=legend, legend_out=False)
    MLU_plot.set(xlim=(10, 45), ylim=(0, 4.5))
    MLU_plot.savefig('{}-MLU.pdf'.format(child_name))


# In[11]: 
Example #7
Source File: run.py    From themarketingtechnologist with Apache License 2.0 5 votes vote down vote up
def visualize_data(self):
        """
        Transform the DataFrame to the 2-dimensional case and visualizes the data. The first tags are used as labels.
        :return:
        """
        logging.debug("Preparing visualization of DataFrame")
        # Reduce dimensionality to 2 features for visualization purposes
        X_visualization = self.reduce_dimensionality(self.X, n_features=2)
        df = self.prepare_dataframe(X_visualization)
        # Set X and Y coordinate for each articles
        df['X coordinate'] = df['coordinates'].apply(lambda x: x[0])
        df['Y coordinate'] = df['coordinates'].apply(lambda x: x[1])
        # Create a list of markers, each tag has its own marker
        n_tags_first = len(self.df['tags_first'].unique())
        markers_choice_list = ['o', 's', '^', '.', 'v', '<', '>', 'D']
        markers_list = [markers_choice_list[i % 8] for i in range(n_tags_first)]
        # Create scatter plot
        sns.lmplot("X coordinate",
                   "Y coordinate",
                   hue="tags_first",
                   data=df,
                   fit_reg=False,
                   markers=markers_list,
                   scatter_kws={"s": 150})
        # Adjust borders and add title
        sns.set(font_scale=2)
        sns.plt.title('Visualization of TMT articles in a 2-dimensional space')
        sns.plt.subplots_adjust(right=0.80, top=0.90, left=0.12, bottom=0.12)
        # Show plot
        sns.plt.show()

    # Train recommender 
Example #8
Source File: plotting.py    From nltools with MIT License 5 votes vote down vote up
def probability_plot(stats_output):
    """ Plot Classification Probability

    Args:
        stats_output: a pandas file with prediction output

    Returns:
        fig: Will return a seaborn scatterplot

    """
    if "Probability_xval" in stats_output.columns:
        sns.lmplot("Y", "Probability_xval", data=stats_output, logistic=True)
    else:
        sns.lmplot("Y", "Probability_all", data=stats_output, logistic=True)
    plt.xlabel("Y", fontsize=16)
    plt.ylabel("Predicted Probability", fontsize=16)
    plt.title("Prediction", fontsize=18)
    return 

    # # and plot the result
    # plt.figure(1, figsize=(4, 3))
    # plt.clf()
    # plt.scatter(X.ravel(), y, color='black', zorder=20)
    # X_test = np.linspace(-5, 10, 300)

    # def model(x):
    #     return 1 / (1 + np.exp(-x))
    # loss = model(X_test * clf.coef_ + clf.intercept_).ravel()
    # plt.plot(X_test, loss, color='blue', linewidth=3) 
Example #9
Source File: plots.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_com_properties_relation(com_clusters, com_fitness_x, com_fitness_y, **kwargs):
    """
    Plot the relation between two properties/fitness function of a clustering

    :param com_clusters:  clustering(s) to analyze (cluster or cluster list)
    :param com_fitness_x: first fitness/community property
    :param com_fitness_y: first fitness/community property
    :param kwargs: parameters for the seaborn lmplot
    :return: a seaborn lmplot

    Example:

    >>> from cdlib import algorithms, viz, evaluation
    >>> import networkx as nx
    >>> g = nx.karate_club_graph()
    >>> coms = algorithms.louvain(g)
    >>> coms2 = algorithms.walktrap(g)
    >>> lmplot = viz.plot_com_properties_relation([coms,coms2],evaluation.size,evaluation.internal_edge_density)
    """
    if isinstance(com_clusters, cdlib.classes.clustering.Clustering):
        com_clusters = [com_clusters]

    for_df = []

    for c in com_clusters:
        x = com_fitness_x(c.graph, c, summary=False)
        y = com_fitness_y(c.graph, c, summary=False)
        for i, vx in enumerate(x):
            for_df.append([c.get_description(), vx, y[i]])

    df = pd.DataFrame(columns=["Method", com_fitness_x.__name__, com_fitness_y.__name__], data=for_df)
    ax = sns.lmplot(x=com_fitness_x.__name__, y=com_fitness_y.__name__, data=df, hue="Method", fit_reg=False,legend=False, x_bins=100,**kwargs)
    plt.legend(loc='best')

    # if log_x:
    #     ax.set_xscale("log")
    # if log_y:
    #     ax.set_yscale("log")
    plt.tight_layout()

    return ax 
Example #10
Source File: TestDataframePlotting.py    From faas-profiler with MIT License 4 votes vote down vote up
def PerfMonPlotter(perf_mon_records, time_window = None):
    """
    For plotting performance monitoring records.
    """
    # Entire records
    pqos_records = perf_mon_records['pqos_records']
    # perf_records = perf_mon_records['perf_records']
    # # Select a time window if provided
    # if time_window is not None:
    #     test_start = pqos_records['timestamp'].min()
    #     time_window = [5, 10]
    #     selection_bounds = [test_start + timedelta(seconds=time_window[0]), \
    #                         test_start + timedelta(seconds=time_window[1])]
    #     pqos_records['In Test Bound'] = (pqos_records['timestamp']>selection_bounds[0]) \
    #                                     & (pqos_records['timestamp']<selection_bounds[1])
    #     perf_records['In Test Bound'] = (perf_records['timestamp']>time_window[0]) \
    #                                     & (perf_records['timestamp']<time_window[1])
    #     pqos_df = pqos_records[pqos_records['In Test Bound']==True]
    #     perf_df = perf_records[perf_records['In Test Bound']==True]

    palette = sns.color_palette("rocket_r", 16)
    
    # 'timestamp','Core','IPC','LLC Misses','LLC Util (KB)','MBL (MB/s)'
    fig, axs = plt.subplots(ncols=2, nrows=2, sharex=True)
    pqos_records_sum = pqos_records.groupby('timestamp').sum()
    pqos_records_sum.plot(y='IPC', ax=axs[0][0])
    pqos_records_sum.plot(y='MBL (MB/s)', ax=axs[0][1])
    pqos_records_sum.plot(y='LLC Util (KB)', ax=axs[1][0])
    pqos_records_sum.plot(y='LLC Misses', ax=axs[1][1])
    axs[0][0].set_ylim([0,20])

    # sns.relplot(data=pqos_records, x='timestamp', y='IPC', hue='Core', kind='line', palette=palette, alpha=0.75)
    # sns.relplot(data=pqos_records, x='timestamp', y='MBL (MB/s)', hue='Core', kind='scatter', palette=palette, alpha=0.75)
    # sns.lmplot(data=pqos_df.groupby('timestamp').sum(), x='IPC', y='MBL (MB/s)', palette=palette,
    #            truncate=True, order=5, fit_reg=False, scatter_kws={'alpha':0.5}, legend_out=False)
    # sns.jointplot(data=pqos_df.groupby('timestamp').sum(), x='LLC Util (KB)', y='MBL (MB/s)', kind="hex", zorder=0)
                #  .plot_joint(sns.kdeplot, zorder=10, n_levels=25, bw='silverman')

    # cpu-cycles,L1-dcache-loads,L1-dcache-load-misses,L1-icache-load-misses,dTLB-load-misses,dTLB-loads,
    # iTLB-load-misses,iTLB-loads,branch-misses,context-switches,cpu-migrations,page-faults
    # sns.relplot(data=perf_records, x='timestamp', y='context-switches', kind='line', palette=palette, alpha=0.75)
    # plt.stackplot(perf_records['timestamp'], perf_records['r4f1'], perf_records['r2f1'], perf_records['r1f1'])
    # sns.relplot(data=perf_df, x='context-switches', y='r1f1', kind='scatter', palette=palette, alpha=0.75)
    # perf_records['Branch Miss Rate (%)'] = 100.0*perf_records['branch-misses']/perf_records['branches']
    # sns.lmplot(data=perf_records, x='context-switches', y='block:block_plug',
    #            truncate=True, order=8, scatter_kws={'alpha':0.5}, legend_out=False)
    # sns.jointplot(data=perf_df, x='dTLB-loads', y='iTLB-loads', kind="hex", zorder=0)

    plt.show()
    plt.close()

    return True