Python seaborn 模块,kdeplot() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用seaborn.kdeplot()

项目:bnn-analysis    作者:myshkov    | 项目源码 | 文件源码
def plot_hist(baseline_samples, target_samples, true_x, true_y):
    baseline_samples = baseline_samples.squeeze()
    target_samples = target_samples.squeeze()

    bmin, bmax = baseline_samples.min(), baseline_samples.max()

    ax = sns.kdeplot(baseline_samples, shade=True, color=(0.6, 0.1, 0.1, 0.2))
    ax = sns.kdeplot(target_samples, shade=True, color=(0.1, 0.1, 0.6, 0.2))
    ax.set_xlim(bmin, bmax)

    y0, y1 = ax.get_ylim()

    plt.plot([true_y, true_y], [0, y1 - (y1 - y0) * 0.01], linewidth=1, color='r')
    plt.title('Predictive' + (f' at {true_x:.2f}' if true_x is not None else ''))

    fig = plt.gcf()
    fig.set_size_inches(9, 9)
    # plt.tight_layout()  # pad=0.4, w_pad=0.5, h_pad=1.0)

    name = utils.DATA_DIR.replace('/', '-')
    # plt.tight_layout(pad=0.6)
    utils.save_fig('predictive-at-point-' + name)
项目:activity-browser    作者:LCA-ActivityBrowser    | 项目源码 | 文件源码
def __init__(self, parent):
        fig = Figure(figsize=(4, 4), dpi=100, tight_layout=True)
        super(DefaultGraph, self).__init__(fig)
        self.setParent(parent)
        sns.set(style="dark")

        for index, s in zip(range(9), np.linspace(0, 3, 10)):
            axes = fig.add_subplot(3, 3, index + 1)
            x, y = np.random.randn(2, 50)
            cmap = sns.cubehelix_palette(start=s, light=1, as_cmap=True)
            sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=axes)
            axes.set_xlim(-3, 3)
            axes.set_ylim(-3, 3)
            axes.set_xticks([])
            axes.set_yticks([])

        fig.suptitle("Activity Browser", y=0.5, fontsize=30, backgroundcolor=(1, 1, 1, 0.5))

        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.updateGeometry()
项目:idea_relations    作者:Noahs-ARK    | 项目源码 | 文件源码
def joint_plot(x, y, xlabel=None,
               ylabel=None, xlim=None, ylim=None,
               loc="best", color='#0485d1',
               size=8, markersize=50, kind="kde",
               scatter_color="r"):
    with sns.axes_style("darkgrid"):
        if xlabel and ylabel:
            g = SubsampleJointGrid(xlabel, ylabel,
                    data=DataFrame(data={xlabel: x, ylabel: y}),
                    space=0.1, ratio=2, size=size, xlim=xlim, ylim=ylim)
        else:
            g = SubsampleJointGrid(x, y, size=size,
                    space=0.1, ratio=2, xlim=xlim, ylim=ylim)
        g.plot_joint(sns.kdeplot, shade=True, cmap="Blues")
        g.plot_sub_joint(plt.scatter, 1000, s=20, c=scatter_color, alpha=0.3)
        g.plot_marginals(sns.distplot, kde=False, rug=False)
        g.annotate(ss.pearsonr, fontsize=25, template="{stat} = {val:.2g}\np = {p:.2g}")
        g.ax_joint.set_yticklabels(g.ax_joint.get_yticks())
        g.ax_joint.set_xticklabels(g.ax_joint.get_xticks())
    return g
项目:unrolled-gan    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}.png".format(dir, filename))
项目:unrolled-gan    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}".format(dir, filename))
项目:My_Script    作者:wen-chen    | 项目源码 | 文件源码
def Features_Cumulative_Frequency(X, y):
    X = pd.DataFrame(X)
    y = pd.DataFrame(y)
    df = pd.concat((y,X), axis=1)
    columns = ['y'] 
    for i in range(1,df.shape[1]):
        columns.append('x' + str(i))
    df.columns = columns

    for i in range(1,df.shape[1]):
        x = 'x' + str(i)
        sns.kdeplot(df[df.y==0][x], cumulative=True, label="y=0")
        sns.kdeplot(df[df.y==1][x], cumulative=True, label="y=1")
        plt.xlabel(x + ' features')
        plt.ylabel('Cumulative frequency')
        plt.show()
项目:nf1_inactivation    作者:greenelab    | 项目源码 | 文件源码
def plot_decision_function(score_df, partition, output_file):
    """
    Plots the decision function for a given partition (either 'train' or
    'test') and saves a figure to file.

    Arguments:
    :param score_df: a specific folds decision scores and status
    :param partition: either 'train' or 'test' will plot performance
    :param output_file: file to output the figure
    """
    ax = sns.kdeplot(score_df.ix[(score_df.status == 1) &
                                 (score_df.partition == partition), :]
                     .decision, color='red', label='Deficient',
                     shade=True)
    ax = sns.kdeplot(score_df.ix[(score_df.status == 0) &
                                 (score_df.partition == partition), :]
                     .decision, color='blue', label='Wild-Type',
                     shade=True)
    ax.set(xlabel='Decision Function', ylabel='Density')
    ax.set_title('Classifier Decision Function')
    sns.despine()
    plt.tight_layout()
    plt.savefig(output_file)
    plt.close()
项目:fitbit-analyzer    作者:5agado    | 项目源码 | 文件源码
def plotCorrelation(stats):
    #columnsToDrop = ['sleep_interval_max_len', 'sleep_interval_min_len',
    #                 'sleep_interval_avg_len', 'sleep_inefficiency',
    #                 'sleep_hours', 'total_hours']

    #stats = stats.drop(columnsToDrop, axis=1)

    g = sns.PairGrid(stats)
    def corrfunc(x, y, **kws):
        r, p = scipystats.pearsonr(x, y)
        ax = plt.gca()
        ax.annotate("r = {:.2f}".format(r),xy=(.1, .9), xycoords=ax.transAxes)
        ax.annotate("p = {:.2f}".format(p),xy=(.2, .8), xycoords=ax.transAxes)
        if p>0.04:
            ax.patch.set_alpha(0.1)

    g.map_upper(plt.scatter)
    g.map_diag(plt.hist)
    g.map_lower(sns.kdeplot, cmap="Blues_d")
    g.map_upper(corrfunc)
    sns.plt.show()
项目:LSGAN    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}.png".format(dir, filename))
项目:LSGAN    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}".format(dir, filename))
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def histogramnd(ax, data, **kwargs):
        """n-dimensional histogram seaborn based
        """
        scatter_data_raw  = data
        scatter_data_cols = ["x_%d" % (i,) for i in range(data.shape[1])]

        # prepare dataframe
        df = pd.DataFrame(scatter_data_raw, columns=scatter_data_cols)

        g = sns.PairGrid(df)
        # g.map_diag(plt.hist)
        g.map_diag(sns.kdeplot)
        g.map_offdiag(plt.hexbin, cmap="gray", gridsize=30, bins="log");

        # logger.log(loglevel_debug, "dir(g)", dir(g))
        # print g.diag_axes
        # print g.axes

        # for i in range(data.shape[1]):
        #     for j in range(data.shape[1]): # 1, 2; 0, 2; 0, 1
        #         if i == j:
        #             continue
        #         # column gives x axis, row gives y axis, thus need to reverse the selection for plotting goal
        #         # g.axes[i,j].plot(df["%s%d" % (self.cols_goal_base, j)], df["%s%d" % (self.cols_goal_base, i)], "ro", alpha=0.5)
        #         g.axes[i,j].plot(df["x_%d" % (j,)], df["x_%d" % (i,)], "ro", alpha=0.5)

        plt.show()


        # run sns scattermatrix on dataframe
        # plot_scattermatrix(df, ax = None)
项目:fake_news    作者:bmassman    | 项目源码 | 文件源码
def word_count_by_label(articles: pd.DataFrame):
    """Show graph of word counts by article label."""
    palette = sns.color_palette(palette='hls', n_colors=2)
    true_news_wc = articles[articles['labels'] == 0]['word_count']
    fake_news_wc = articles[articles['labels'] == 1]['word_count']
    sns.kdeplot(true_news_wc, bw=3, color=palette[0], label='True News')
    sns.kdeplot(fake_news_wc, bw=3, color=palette[1], label='Fake News')
    sns.plt.legend()
    sns.plt.show()
项目:astetik    作者:mikkokotila    | 项目源码 | 文件源码
def kde(x,y,title='',color='YlGnBu',xscale='linear',yscale='linear'):

    sns.set_style('white')
    sns.set_context('notebook', font_scale=1, rc={"lines.linewidth": 0.5})
    g = sns.kdeplot(x,y,shade=True, cut=2, cmap=color, shade_lowest=False, legend=True, set_title="test")
    plt.tick_params(axis='both', which='major', pad=10)
    sns.plt.title(title)

    g.set(xscale=xscale)
    g.set(yscale=yscale)

    sns.despine()
项目:Waskom_PNAS_2017    作者:WagnerLabPapers    | 项目源码 | 文件源码
def plot_kdes(subjects, axes):

    ftemp = "correlation_analysis/{}_{}_ifs.pkz"
    for subj, ax in zip(subjects, axes):

        sticks = moss.load_pkl(ftemp.format(subj, "sticks")).corrmat
        rest = moss.load_pkl(ftemp.format(subj, "rest")).corrmat

        triu = np.triu_indices_from(rest, 1)

        sns.kdeplot(sticks[triu], color=".15",
                    label="residual", ax=ax)
        sns.kdeplot(rest[triu], color=".45", dashes=[4, 1],
                    label="resting", ax=ax)

    plt.setp(axes,
             xlim=(-.25, .8), ylim=(0, 17),
             xticks=np.linspace(-.2, .8, 6),
             yticks=[])

    for ax in axes:
        sns.despine(ax=ax, left=True, trim=True)
        plt.setp(ax.get_xticklabels(), size=6)
        plt.setp(ax.get_yticklabels(), size=6)

    axes[0].legend(bbox_to_anchor=(1.2, .8))
    for ax in axes[1:]:
        ax.legend_ = None
项目:ABtests    作者:leodema    | 项目源码 | 文件源码
def myplot(x, y):
    x, y = np.array(x), np.array(y)

    # bins = np.linspace(-10, 10, 100)
    x1 = sns.kdeplot(x, shade=True)
    x2 = sns.kdeplot(y, shade=True)
    x1.set_xlabel('Value')
    x2.set_ylabel('Percentage')
    # pyplot.hist(x, bins, alpha=0.5, label='x')
    # pyplot.hist(y, bins, alpha=0.5, label='y')

    pyplot.legend(loc='upper right')
    pyplot.title('Cumulative distributions')
    pyplot.show()
项目:pyaneti    作者:oscaribv    | 项目源码 | 文件源码
def create_plot_posterior(params,plabs,cbars='red',nb=50,num=[]):
  if ( len(num) < 2 ):
    n = range(0,len(params))
  else:
    n = num
  plt.figure(1,figsize=(12,4*(len(n))/2))
  gs = gridspec.GridSpec(nrows=(len(n)+1)/2,ncols=2)
  j = 0
  for i in n:
    plt.subplot(gs[j])
    vpar, lpar, rpar = find_vals_perc(params[i],1.0)
    moda = my_mode(params[i])
    #best_val = params[i][minchi2_index]
    #plt.axvline(x=best_val,c='yellow')
    plt.axvline(x=vpar,c=cbars)
    plt.axvline(x=moda,c='y',ls='-.')
    plt.axvline(x=vpar-lpar,c=cbars,ls='--')
    plt.axvline(x=vpar+rpar,c=cbars,ls='--')
    plt.xlabel(plabs[i])
    plt.tick_params( axis='y',which='both',direction='in')
    plt.tick_params( axis='x',which='both',direction='in')
    if ( is_seaborn_plot ):
      sns.kdeplot(params[i], shade=True)
    else:
      plt.hist(params[i],normed=True,bins=nb)
    j = j + 1

  fname = outdir+'/'+star+'_posterior.pdf'
  print 'Creating ', fname
  plt.savefig(fname,format='pdf',bbox_inches='tight')
  plt.close()
项目:Comparative-Annotation-Toolkit    作者:ComparativeGenomicsToolkit    | 项目源码 | 文件源码
def improvement_plot(consensus_data, ordered_genomes, improvement_tgt):
    def do_kdeplot(x, y, ax, n_levels=None, bw='scott'):
        try:
            sns.kdeplot(x, y, ax=ax, cut=0, cmap='Purples_d', shade=True, shade_lowest=False, n_levels=n_levels, bw=bw,
                        rasterized=True)
        except:
            logger.warning('Unable to do a KDE fit to AUGUSTUS improvement.')
            pass

    with improvement_tgt.open('w') as outf, PdfPages(outf) as pdf, sns.axes_style("whitegrid"):
        for genome in ordered_genomes:
            data = pd.DataFrame(consensus_data[genome]['Evaluation Improvement']['changes'])
            unchanged = consensus_data[genome]['Evaluation Improvement']['unchanged']
            if len(data) == 0:
                continue
            data.columns = ['transMap original introns',
                            'transMap intron annotation support',
                            'transMap intron RNA support',
                            'Original introns',
                            'Intron annotation support',
                            'Intron RNA support',
                            'transMap alignment goodness',
                            'Alignment goodness']
            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2)
            for ax in [ax1, ax2, ax3]:  # goodness plots are allowed to auto-set scale
                ax.set_xlim(0, 100)
                ax.set_ylim(0, 100)
            goodness_min = min(data['Alignment goodness'])
            ax4.set_xlim(goodness_min, 100)
            ax4.set_ylim(goodness_min, 100)
            do_kdeplot(data['transMap original introns'], data['Original introns'], ax1, n_levels=25, bw=2)
            sns.regplot(x=data['transMap original introns'], y=data['Original introns'], ax=ax1,
                        color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False)
            do_kdeplot(data['transMap intron annotation support'], data['Intron annotation support'], ax2,
                       n_levels=25, bw=2)
            sns.regplot(x=data['transMap intron annotation support'], y=data['Intron annotation support'], ax=ax2,
                        color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False)
            do_kdeplot(data['transMap intron RNA support'], data['Intron RNA support'], ax3, n_levels=25, bw=2)
            sns.regplot(x=data['transMap intron RNA support'], y=data['Intron RNA support'], ax=ax3,
                        color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False)
            do_kdeplot(data['transMap alignment goodness'], data['Alignment goodness'], ax4, n_levels=20, bw=1)
            sns.regplot(x=data['transMap alignment goodness'], y=data['Alignment goodness'], ax=ax4,
                        color='#A9B36F', scatter_kws={"s": 3, 'alpha': 0.7, 'rasterized': True}, fit_reg=False)
            fig.suptitle('AUGUSTUS metric improvements for {:,} transcripts in {}.\n'
                         '{:,} transMap transcripts were chosen.'.format(len(data), genome, unchanged))
            for ax in [ax1, ax2, ax3, ax4]:
                ax.set(adjustable='box-forced', aspect='equal')
            fig.subplots_adjust(hspace=0.3)
            multipage_close(pdf, tight_layout=False)
项目:Data_Analysis    作者:crown-prince    | 项目源码 | 文件源码
def main():
    #?????????????????, ?????????
    stock_list = {"zsyh":"600036","jsyh":"601939","szzs":"000001","pfyh":"600000","msyh":"600061"}

    for stock, code in stock_list.items():
        globals()[stock] = tsh.get_hist_data(code,start="2015-01-01",end="2016-04-16")
        #code:?????start:?????end:????
    #print(zsyh) #???????????
    make_end_line()
    print(zsyh.head())
    make_end_line()
    print(zsyh.columns)
    make_end_line()
    """
    ????

    date???
    open????
    high????
    close????
    low????
    volume????
    price_change?????
    p_change????
    ma5?5???
    ma10?10???
    ma20: 20???
    v_ma5: 5???
    v_ma10: 10???
    v_ma20: 20???
    turnover:???[???????]
    """
    print(zsyh.describe())
    make_end_line()
    print(zsyh.info())
    make_end_line()
    plt.show(zsyh["close"].plot(figsize=(12,8))) #???????????
    #pd.set_option("display.float_format", lambda x: "%10.3f" % x) 
    plt.show(zsyh["volume"].plot(figsize=(12,8)))
    zsyh[["close","ma5","ma10","ma20"]].plot(subplots = True)
    plt.show()
    plt.show(zsyh[["close","ma5","ma10","ma20"]].plot(figsize=(12,8),linewidth=2))
    plt.show(zsyh["p_change"].plot())
    plt.show(zsyh["p_change"].plot(figsize=(10,4),legend=True,linestyle="--",marker="o"))
    #???????????
    plt.show(zsyh["p_change"].hist(bins=20))
    plt.show(zsyh["p_change"].plot.kde()) #?????
                                          #?????(kernel density estimation)?????????????????
    plt.show(sns.kdeplot(zsyh["p_change"].dropna()))
    plt.show(sns.distplot(zsyh["p_change"].dropna())) #??????????????????????