Python seaborn.despine() Examples

The following are 30 code examples of seaborn.despine(). 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: brute_force_plotter.py    From brute-force-plotter with MIT License 7 votes vote down vote up
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
    sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
    sns.boxplot(
        category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
    )
    sns.violinplot(
        category_col,
        numeric_col,
        data=data,
        kind="violin",
        inner="quartile",
        scale="count",
        split=True,
        ax=axes[3],
    )
    sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
    sns.despine(left=True) 
Example #2
Source File: analysis.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_pca(pX, palette='Spectral', labels=None, ax=None, colors=None):
    """Plot PCA result, input should be a dataframe"""

    if ax==None:
        fig,ax=plt.subplots(1,1,figsize=(6,6))
    cats = pX.index.unique()
    colors = sns.mpl_palette(palette, len(cats)+1)
    print (len(cats), len(colors))
    for c, i in zip(colors, cats):
        #print (i, len(pX.ix[i]))
        #if not i in pX.index: continue
        ax.scatter(pX.ix[i, 0], pX.ix[i, 1], color=c, s=90, label=i,
                   lw=.8, edgecolor='black', alpha=0.8)
    ax.set_xlabel('PC1')
    ax.set_ylabel('PC2')
    i=0
    if labels is not None:
        for n, point in pX.iterrows():
            l=labels[i]
            ax.text(point[0]+.1, point[1]+.1, str(l),fontsize=(9))
            i+=1
    ax.legend(fontsize=10,bbox_to_anchor=(1.5, 1.05))
    sns.despine()
    plt.tight_layout()
    return 
Example #3
Source File: runner.py    From geoseg with MIT License 6 votes vote down vote up
def learning_curve(self, idxs=[2,3,5,6]):
        import seaborn as sns
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        # set style
        sns.set_context("paper", font_scale=1.5,)
        # sns.set_style("ticks", {
        #     "font.family": "Times New Roman",
        #     "font.serif": ["Times", "Palatino", "serif"]})

        for idx in idxs:
            plt.plot(self.logs[self.args.trigger],
                     self.logs[self.header[idx]], label=self.header[idx])
        plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator)))
        if self.args.trigger == 'epoch':
            plt.xlabel("Epochs")
        else:
            plt.xlabel("Iterations")
        plt.suptitle("Training log of {}".format(self.method))
        # remove top&left line
        # sns.despine()
        plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
        plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)),
                    format='png', bbox_inches='tight', dpi=144) 
Example #4
Source File: plot_utils.py    From jqfactor_analyzer with MIT License 6 votes vote down vote up
def customize(func):

    @wraps(func)
    def call_w_context(*args, **kwargs):

        if not PlotConfig.FONT_SETTED:
            _use_chinese(True)

        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context 
Example #5
Source File: gan_toy1d.py    From gan with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, save_animation=False, fps=30):
        """Initialize the helper class.

        :param save_animation: Whether the animation should be saved as a gif. Requires the ImageMagick library.
        :param fps: The number of frames per second when saving the gif animation.
        """
        self.save_animation = save_animation
        self.fps = fps
        self.figure, (self.ax1, self.ax2) = plt.subplots(1, 2, figsize=(8, 4))
        self.figure.suptitle("1D GAN")
        sns.set(color_codes=True, style='white', palette='colorblind')
        sns.despine(self.figure)
        plt.show(block=False)

        if self.save_animation:
            self.writer = ImageMagickWriter(fps=self.fps)
            self.writer.setup(self.figure, 'demo.gif', dpi=100) 
Example #6
Source File: figure.py    From DrugEx with MIT License 6 votes vote down vote up
def fig6():
    """ violin plot for the physicochemical proerties comparison.
        A: molecules generated by pre-trained model v.s. ZINC set.
        B: molecules generated by fine-tuned model v.s. A2AR set.
    """
    plt.figure(figsize=(12, 6))
    plt.subplot(121)
    sns.set(style="white", palette="pastel", color_codes=True)
    df = properties(['data/ZINC_B.txt', 'mol_p.txt'], ['ZINC Dataset', 'Pre-trained Model'])
    sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, split=True, bw=1)
    sns.despine(left=True)
    plt.ylim([0.0, 18.0])
    plt.xlabel('Structural Properties')

    plt.subplot(122)
    df = properties(['data/CHEMBL251.txt', 'mol_ex.txt'], ['A2AR Dataset', 'Fine-tuned Model'])
    sns.set(style="white", palette="pastel", color_codes=True)
    sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, split=True, bw=1)
    sns.despine(left=True)
    plt.ylim([0.0, 18.0])
    plt.xlabel('Structural Properties')
    plt.tight_layout()
    plt.savefig('Figure_6.tif', dpi=300) 
Example #7
Source File: figure.py    From DrugEx with MIT License 6 votes vote down vote up
def fig9():
    """ violin plot for the physicochemical proerties comparison.
            1: molecules generated by DrugEx with pre-trained model as exploration network.
            2: molecules generated by DrugEx with fine-tuned model as exploration network.
        """
    fig = plt.figure(figsize=(12, 12))
    ax1 = fig.add_subplot(211)
    sns.set(style="white", palette="pastel", color_codes=True)
    df = properties(mol_paths + real_path, labels + real_label, is_active=True)
    sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, bw=0.8)
    sns.despine(left=True)
    ax1.set(ylim=[0.0, 15.0], xlabel='Structural Properties')

    ax2 = fig.add_subplot(212)
    df = properties(mol_paths1 + real_path, labels + real_label, is_active=True)
    sns.set(style="white", palette="pastel", color_codes=True)
    sns.violinplot(x='Property', y='Number', hue='Set', data=df, linewidth=1, bw=0.8)
    sns.despine(left=True)
    ax2.set(ylim=[0.0, 15.0], xlabel='Structural Properties')
    fig.tight_layout()
    fig.savefig('Figure_9.tif', dpi=300) 
Example #8
Source File: plotter.py    From message-analyser with MIT License 6 votes vote down vote up
def barplot_messages_per_weekday(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid", palette="pastel")

    messages_per_weekday = stools.get_messages_per_weekday(msgs)
    labels = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    ax = sns.barplot(x=labels, y=[len(weekday) for weekday in messages_per_weekday.values()],
                     label=your_name, color="b")
    sns.set_color_codes("muted")
    sns.barplot(x=labels,
                y=[len([msg for msg in weekday if msg.author == target_name])
                   for weekday in messages_per_weekday.values()],
                label=target_name, color="b")

    ax.legend(ncol=2, loc="lower right", frameon=True)
    ax.set(ylabel="messages")
    sns.despine(right=True, top=True)

    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, barplot_messages_per_weekday.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{barplot_messages_per_weekday.__name__} was created.")
    plt.close("all") 
Example #9
Source File: modeling.py    From wgd with GNU General Public License v3.0 6 votes vote down vote up
def plot_all_models_gmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of GMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 3, figsize=(15, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
    sns.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file) 
Example #10
Source File: modeling.py    From wgd with GNU General Public License v3.0 6 votes vote down vote up
def plot_all_models_bgmm(models, data, l, u, bins, out_file):
    """
    Plot a bunch of BGMMs.

    :param models: list of GMM model objects
    :param data: Ks array
    :param l: lower Ks limit
    :param u: upper Ks limit
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    fig, axes = plt.subplots(len(models), 4, figsize=(20, 3 * len(models)))
    for i, model in enumerate(models):
        plot_mixture(model, data, axes[i, 0], l, u, bins=bins)
        plot_mixture(model, data, axes[i, 1], log=True, l=np.log(l + 0.0001),
                     u=np.log(u), bins=bins)
        plot_probs(model, axes[i, 2], l, u)
        plot_bars_weights(model, axes[i, 3])
    sns.despine(offset=5)
    fig.tight_layout()
    fig.savefig(out_file) 
Example #11
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_read_count_dists(counts, h=8, n=50):
    """Boxplots of read count distributions """

    scols,ncols = base.get_column_names(counts)
    df = counts.sort_values(by='mean_norm',ascending=False)[:n]
    df = df.set_index('name')[ncols]
    t = df.T
    w = int(h*(len(df)/60.0))+4
    fig, ax = plt.subplots(figsize=(w,h))
    if len(scols) > 1:
        sns.stripplot(data=t,linewidth=1.0,palette='coolwarm_r')
        ax.xaxis.grid(True)
    else:
        df.plot(kind='bar',ax=ax)
    sns.despine(offset=10,trim=True)
    ax.set_yscale('log')
    plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
    plt.ylabel('read count')
    #print (df.index)
    #plt.tight_layout()
    fig.subplots_adjust(bottom=0.2,top=0.9)
    return fig 
Example #12
Source File: distanceWeightStatistic.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def geoValueWeightedVisulization(valueDes):
    valueDes["ID"]=valueDes.index
    sns.set(style="whitegrid")
    # Make the PairGrid
    extractedColumns=["count","mean","std","max"]
    g=sns.PairGrid(valueDes.sort_values("count", ascending=False),x_vars=extractedColumns, y_vars=["ID"],height=10, aspect=.25)
    # Draw a dot plot using the stripplot function
    g.map(sns.stripplot, size=10, orient="h",palette="ch:s=1,r=-.1,h=1_r", linewidth=1, edgecolor="w")    
    # Use the same x axis limits on all columns and add better labels
    g.set(xlabel="value", ylabel="") #g.set(xlim=(0, 25), xlabel="Crashes", ylabel="")
    # Use semantically meaningful titles for the columns
    titles=valueDes.columns.tolist() 
    for ax, title in zip(g.axes.flat, titles):
        # Set a different title for each axes
        ax.set(title=title)
        # Make the grid horizontal instead of vertical
        ax.xaxis.grid(False)
        ax.yaxis.grid(True)
    sns.despine(left=True, bottom=True) 
Example #13
Source File: TargetAnalysisContinuous.py    From exploripy with MIT License 6 votes vote down vote up
def BoxPlot(self, feature):		
		fig, ax = plt.subplots()
		ax = sns.boxplot(y=self.df[feature], ax=ax)
		box = ax.artists[0]
		indices = random.sample(range(len(self.SelectedColors)), 2)
		colors=[self.SelectedColors[i] for i in sorted(indices)]
		box.set_facecolor(colors[0])
		box.set_edgecolor(colors[1])
		sns.despine(offset=10, trim=True)
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+feature + '.png')
		if platform.system() =='Linux':
			OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/' + feature + '.png')
		plt.savefig(OutFileName)
		
		return OutFileName 
Example #14
Source File: EDA.py    From exploripy with MIT License 6 votes vote down vote up
def BoxPlot(self,var):

		start = time.time()
		fig, ax = plt.subplots()
		ax = sns.boxplot(y=self.df[var], ax=ax)
		box = ax.artists[0]
		indices = random.sample(range(len(self.SelectedColors)), 2)
		colors=[self.SelectedColors[i] for i in sorted(indices)]
		box.set_facecolor(colors[0])
		box.set_edgecolor(colors[1])
		sns.despine(offset=10, trim=True)
		
		
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+var + '.png')
		
		plt.savefig(OutFileName)
		end = time.time()
		if self.debug == 'YES':
			print('BoxPlot',end-start)
		
		return OutFileName 
Example #15
Source File: plotting_utils.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def customize(func):
    """
    修饰器,设置输出图像内容与风格
    """

    @wraps(func)
    def call_w_context(*args, **kwargs):
        set_context = kwargs.pop("set_context", True)
        if set_context:
            color_palette = sns.color_palette("colorblind")
            with plotting_context(), axes_style(), color_palette:
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context 
Example #16
Source File: TargetAnalysisCategorical.py    From exploripy with MIT License 6 votes vote down vote up
def BoxPlot(self, feature):		
		fig, ax = plt.subplots()
		ax = sns.boxplot(y=self.df[feature], ax=ax)
		box = ax.artists[0]
		indices = random.sample(range(len(self.SelectedColors)), 2)
		colors=[self.SelectedColors[i] for i in sorted(indices)]
		box.set_facecolor(colors[0])
		box.set_edgecolor(colors[1])
		sns.despine(offset=10, trim=True)
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+feature + '.png')
		if platform.system() == 'Linux':
			out_filename = os.path.join(this_dir, 'ExploriPy/HTMLTemplate/dist/output/'+feature + '.png')
		plt.savefig(OutFileName)
		
		return OutFileName 
Example #17
Source File: plotlib.py    From mCaller with MIT License 6 votes vote down vote up
def plot_change_by_pos(diffs_by_context,plottype='box'):
    fig = plt.figure(figsize=(6,4))
    changes_by_position = {'position':[],'base':[],'diff':[]}
    for lab in diffs_by_context:
        for context in diffs_by_context[lab]:
            for entry in diffs_by_context[lab][context]:
                for pos,diff in enumerate(entry[:-1]):
                    changes_by_position['position'].append(pos+1)
                    changes_by_position['base'].append(lab)
                    changes_by_position['diff'].append(diff)
    dPos = pd.DataFrame(changes_by_position)
    if plottype == 'box':
        sns.boxplot(x="position", y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    elif plottype == 'violin':
        sns.violinplot(x="position",y="diff", hue="base", data=dPos, palette=[cols[base],cols[methbase]])
    sns.despine(trim=False)
    plt.xlabel('Adenine Position in 6-mer')
    plt.ylabel('Measured - Expected Current (pA)')
    plt.ylim([-20,20])
    plt.legend(title='',loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True)
    plt.savefig('change_by_position_box.pdf',transparent=True,dpi=500, bbox_inches='tight') 
Example #18
Source File: chart.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def image(path: str, costs: Dict[str, int]) -> str:
    ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
    xs = [costs.get(k, 0) for k in ys]
    sns.set_style('white')
    sns.set(font='Concourse C3', font_scale=3)
    g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
    g.axes.yaxis.set_ticklabels([])
    rects = g.patches
    sns.set(font='Concourse C3', font_scale=2)
    for rect, label in zip(rects, xs):
        if label == 0:
            continue
        height = rect.get_height()
        g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
    g.margins(y=0, x=0)
    sns.despine(left=True, bottom=True)
    g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
    plt.clf() # Clear all data from matplotlib so it does not persist across requests.
    return path 
Example #19
Source File: utils.py    From jira-agile-metrics with MIT License 5 votes vote down vote up
def set_chart_style(style="whitegrid", despine=True):
    sns.set_style(style)
    if despine:
        sns.despine() 
Example #20
Source File: pipeline_rnaseqqc.py    From CGATPipelines with MIT License 5 votes vote down vote up
def plotStrandednessSalmon(infile, outfile):
    '''
    Plots a bar plot of the salmon strandness estimates
    as counts per sample.
    '''
    sns.set_style('ticks')
    tab = pd.read_csv(infile, sep="\t")
    counttab = tab[tab.columns[7:]]
    f = plt.figure(figsize=(10, 7))
    a = f.add_axes([0.1, 0.1, 0.6, 0.75])
    x = 0
    colors = sns.color_palette("Dark2", 10)
    a.set_ylim(0, max(counttab.values[0]) + max(counttab.values[0]) * 0.1)
    for item in counttab.columns:
        a.bar(range(x, x + len(tab)), tab[item], color=colors)
        x += len(tab)
    a.ticklabel_format(style='plain')
    a.vlines(np.arange(-0.4, a.get_xlim()[1], len(tab)),
             a.get_ylim()[0], a.get_ylim()[1], lw=0.5)
    a.set_xticks(np.arange(0 + len(tab) / 2, a.get_xlim()[1],
                           len(tab)))
    a.set_xticklabels(counttab.columns)
    sns.despine()
    patches = []
    for c in colors[0:len(tab)]:
        patches.append(mpatches.Patch(color=c))
    l = f.legend(labels=tab['sample'], handles=patches, loc=1)
    f.suptitle('Strandedness Estimates')
    f.savefig(outfile)

###################################################################
# Main pipeline tasks
################################################################### 
Example #21
Source File: plot_kmer_evenness.py    From EdwardsLab with MIT License 5 votes vote down vote up
def plot_evenness(df, output, verbose=False):
    if verbose:
        sys.stderr.write(f"{bcolors.GREEN}Plotting evenness{bcolors.ENDC}\n")
    sns.violinplot(data=df, x='kmer', y='Evenness')
    sns.despine(offset=10, trim=True)
    plt.savefig(f"{output}.evenness.png")
    plt.clf() 
Example #22
Source File: plot_kmer_evenness.py    From EdwardsLab with MIT License 5 votes vote down vote up
def plot_swarm_evenness(df, output, verbose=False):
    if verbose:
        sys.stderr.write(f"{bcolors.GREEN}Plotting swarmed evenness{bcolors.ENDC}\n")
    sns.violinplot(data=df, x='kmer', y='Evenness')
    sns.swarmplot(data=df, x='kmer', y='Evenness')
    sns.despine(offset=10, trim=True)
    plt.savefig(f"{output}.swarm.evenness.png")
    plt.clf() 
Example #23
Source File: plot_kmer_evenness.py    From EdwardsLab with MIT License 5 votes vote down vote up
def plot_shannon(df, output, verbose=False):
    if verbose:
        sys.stderr.write(f"{bcolors.GREEN}Plotting swarmed shannon{bcolors.ENDC}\n")
    sns.violinplot(data=df, x='kmer', y='Shannon')
    sns.swarmplot(data=df, x='kmer', y='Shannon')
    sns.despine(offset=10, trim=True)
    plt.savefig(f"{output}.shannon.png")
    plt.clf() 
Example #24
Source File: esrunner.py    From geoseg with MIT License 5 votes vote down vote up
def learning_curve(self, idxs=[2,3,5,6]):
        import seaborn as sns
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        # set style
        sns.set_context("paper", font_scale=1.5,)
        # sns.set_style("ticks", {
        #     "font.family": "Times New Roman",
        #     "font.serif": ["Times", "Palatino", "serif"]})

        for idx in idxs:
            plt.plot(self.logs[self.args.trigger],
                     self.logs[self.header[idx]], label=self.header[idx])
        plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator)))
        if self.args.trigger == 'epoch':
            plt.xlabel("Epochs")
        else:
            plt.xlabel("Iterations")
        plt.suptitle("Training log of {}".format(self.method))
        # remove top&left line
        # sns.despine()
        plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
        plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)),
                    format='png', bbox_inches='tight', dpi=144)
        # plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.eps'.format(self.repr)),
        #             format='eps', bbox_inches='tight', dpi=300)
        return 0 
Example #25
Source File: plotlib.py    From mCaller with MIT License 5 votes vote down vote up
def plot_training_probabilities(prob_scores,tb):
    #prob_scores = {'m6A':[0.9,0.4,...],'A':[0.1,0.5,0.2,...]}
    sns.set_style('darkgrid')
    sns.set_palette(['#55B196','#B4656F'])
    fig = plt.figure(figsize=(3,4))
    prob_dict = {'probability':prob_scores[base]+prob_scores[modbase],'base':[base]*len(prob_scores[base])+[modbase]*len(prob_scores[modbase])}
    prob_db = pd.DataFrame(prob_dict)
    sns.boxplot(x="base", y="probability", data=prob_db)
    sns.despine()
    plt.show()
    plt.savefig('training_probability_'+tb+'_model_boxplot.pdf',transparent=True,dpi=500,bbox_inches='tight') 
Example #26
Source File: modeling.py    From wgd with GNU General Public License v3.0 5 votes vote down vote up
def reflected_kde(df, min_ks, max_ks, bandwidth, bins, out_file):
    """
    Perform Kernel density estimation (KDE) with reflected data.
    The data frame is assumed to be grouped already by 'Node'.

    :param df: data frame
    :param min_ks: minimum Ks value (best is to use 0, for reflection purposes)
    :param max_ks: maximum Ks value
    :param bandwidth: bandwidth (None results in Scott's rule of thumb)
    :param bins: number of histogram bins
    :param out_file: output file
    :return: nada
    """
    ks = np.array(df['Ks'])
    ks_reflected = reflect(ks)
    fig, ax = plt.subplots(figsize=(9, 4))
    if bandwidth:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                kde_kws={"bw": bandwidth},
                color="k"
        )
    else:
        ax = sns.distplot(
                ks_reflected, bins=bins * 2, ax=ax,
                hist_kws={"rwidth": 0.8, "color": "k", "alpha": 0.2},
                color="k"
        )
    ax.set_xlim(min_ks, max_ks)
    sns.despine(offset=5, trim=False)
    ax.set_ylabel("Density")
    ax.set_xlabel("$K_{\mathrm{S}}$")
    fig.savefig(out_file, bbox_inches='tight') 
Example #27
Source File: TargetAnalysisContinuous.py    From exploripy with MIT License 5 votes vote down vote up
def RegPlot (self, feature, target):
		fig, ax = plt.subplots()		 
		#color=self.SelectedColors[random.sample(range(len(self.SelectedColors)), 1)] 
		ax = sns.regplot(x=feature, y=target, data=self.df, ax=ax, color=random.choice(self.SelectedColors))
		
		sns.despine(offset=10, trim=True)
		this_dir, this_filename = os.path.split(__file__)
		OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/'+feature + '_regPlot.png')
		if platform.system() =='Linux':
			OutFileName = os.path.join(this_dir, 'HTMLTemplate/dist/output/' + feature + '_regPlot.png')
		plt.savefig(OutFileName)
		
		return OutFileName 
Example #28
Source File: brute_force_plotter.py    From brute-force-plotter with MIT License 5 votes vote down vote up
def heatmap(data, file_name=None):
    cmap = "BuGn" if (data.values >= 0).all() else "coolwarm"
    sns.heatmap(data=data, annot=True, fmt="d", cmap=cmap)
    sns.despine(left=True) 
Example #29
Source File: plot_posterior.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _create_joint_axis(self, figure=None, subplot_spec=None, figsize=None, textsize=None):
        figsize, ax_labelsize, _, xt_labelsize, linewidth, _ = _scale_fig_size(figsize, textsize)
        # Instantiate figure and grid

        if figure is None:
            fig, _ = plt.subplots(0, 0, figsize=figsize, constrained_layout=True)
        else:
            fig = figure

        if subplot_spec is None:
            grid = plt.GridSpec(4, 4, hspace=0.1, wspace=0.1, figure=fig)
        else:
            grid = gridspect.GridSpecFromSubplotSpec(4, 4, subplot_spec=subplot_spec)

        # Set up main plot
        self.axjoin = fig.add_subplot(grid[1:, :-1])

        # Set up top KDE
        self.ax_hist_x = fig.add_subplot(grid[0, :-1], sharex=self.axjoin)
        self.ax_hist_x.tick_params(labelleft=False, labelbottom=False)

        # Set up right KDE
        self.ax_hist_y = fig.add_subplot(grid[1:, -1], sharey=self.axjoin)
        self.ax_hist_y.tick_params(labelleft=False, labelbottom=False)
        sns.despine(left=True, bottom=True)

        return self.axjoin, self.ax_hist_x, self.ax_hist_y 
Example #30
Source File: brute_force_plotter.py    From brute-force-plotter with MIT License 5 votes vote down vote up
def scatter_plot(data, col1, col2, file_name=None):
    sns.regplot(x=col1, y=col2, data=data, fit_reg=False)
    sns.despine(left=True)