Python seaborn.jointplot() Examples

The following are 22 code examples of seaborn.jointplot(). 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: mouse_brain_astrocyte.py    From geosketch with MIT License 7 votes vote down vote up
def astro_oligo_joint(X, genes, gene1, gene2, labels, focus, name):
    X = X.toarray()

    gidx1 = list(genes).index(gene1)
    gidx2 = list(genes).index(gene2)

    idx = labels == focus

    x1 = X[(idx, gidx1)]
    x2 = X[(idx, gidx2)]

    plt.figure()
    sns.jointplot(
        x1, x2, kind='scatter', space=0, alpha=0.3
    ).plot_joint(sns.kdeplot, zorder=0, n_levels=10)
    plt.savefig('{}_joint_{}_{}_{}.png'.format(name, focus, gene1, gene2)) 
Example #2
Source File: mouse_brain_subcluster.py    From geosketch with MIT License 6 votes vote down vote up
def astro_oligo_joint(X, genes, gene1, gene2, labels, focus, name):
    X = X.toarray()

    gidx1 = list(genes).index(gene1)
    gidx2 = list(genes).index(gene2)

    idx = labels == focus

    x1 = X[(idx, gidx1)]
    x2 = X[(idx, gidx2)]

    plt.figure()
    sns.jointplot(
        x1, x2, kind='scatter', space=0, alpha=0.3
    ).plot_joint(sns.kdeplot, zorder=0, n_levels=10)
    plt.savefig('{}_joint_{}_{}_{}.png'.format(name, focus, gene1, gene2)) 
Example #3
Source File: stock_visualizer.py    From stock-analysis with MIT License 6 votes vote down vote up
def jointplot(self, other, column, **kwargs):
        """
        Generate a seaborn jointplot for given column in asset compared to
        another asset.

        Parameters:
            - other: The other asset's dataframe
            - column: The column name to use for the comparison.
            - kwargs: Keyword arguments to pass down to `sns.pairplot()`

        Returns:
            A seaborn jointplot
        """
        return sns.jointplot(
            x=self.data[column],
            y=other[column],
            **kwargs
        ) 
Example #4
Source File: create_retrosynthesis_plots.py    From molecule-chef with GNU General Public License v3.0 6 votes vote down vote up
def produce_the_kde_plot(cycles, color, save_name):
    ground_truth_and_suggested = [(eval_code.get_best_qed_from_smiles_bag(elem['ground_truth_product']),
                                   eval_code.get_best_qed_from_smiles_bag(elem['suggested_product']))
                                         for elem in cycles]
    len_out = len(ground_truth_and_suggested)
    ground_truth_and_suggested = [elem for elem in ground_truth_and_suggested if elem[1] != -np.inf]
    len_filter = len(ground_truth_and_suggested)
    num_discarding = len_out - len_filter
    if num_discarding:
        warnings.warn(f"Discarding {num_discarding} our of {len_out} as no successful reconstruction")
    ground_truth_and_suggested = np.array(ground_truth_and_suggested)
    ground_truth_product_qed = ground_truth_and_suggested[:, 0]
    suggested_product_qed = ground_truth_and_suggested[:, 1]

    g = sns.jointplot(x=ground_truth_product_qed, y=suggested_product_qed, kind="kde", color=color,
                      )
    g.set_axis_labels("product's QED", "reconstructed product's QED", fontsize=16)
    rsquare = lambda a, b: stats.pearsonr(ground_truth_product_qed, suggested_product_qed)[0] ** 2
    g = g.annotate(rsquare, template="{stat}: {val:.2f}",
                   stat="$R^2$", loc="upper left", fontsize=12)
    print(f"Rsquare: {stats.pearsonr(ground_truth_product_qed, suggested_product_qed)[0] ** 2}")
    print(f"scipystats: {stats.linregress(ground_truth_product_qed, suggested_product_qed)}")
    plt.tight_layout()
    plt.savefig(f"{save_name}.pdf") 
Example #5
Source File: plotUtils.py    From pyodds with MIT License 6 votes vote down vote up
def visualize_distribution(X,prediction,score,path=None):
    """
    Visualize the original density distribution of the data in 2-dimension space.

    Parameters
    ----------
    X: numpy array of shape (n_test, n_features)
        Test data.
    prediction: numpy array of shape (n_test, )
        The prediction result of the test data.
    score: numpy array of shape (n_test, )
        The outlier score of the test data.
    path: string
        The saving path for result figures.
    """

    sns.set(style="ticks")
    X=X.to_numpy()
    X_embedding = TSNE(n_components=2).fit_transform(X)
    sns_plot=sns.jointplot(X_embedding[:,1],X_embedding[:,0], kind="kde", space=0, color="#4CB391")
    if path:
        sns_plot.savefig(path+'/distribution.png')
    plt.show() 
Example #6
Source File: plotting.py    From MJHMC with GNU General Public License v2.0 6 votes vote down vote up
def gauss_2d(nsamples=1000):
    """
    Another simple test plot
    1d gaussian sampled from each sampler visualized as a joint 2d gaussian
    """
    gaussian = TestGaussian(ndims=1)
    control = HMCBase(distribution=gaussian)
    experimental = MarkovJumpHMC(distribution=gaussian, resample=False)


    with sns.axes_style("white"):
        sns.jointplot(
            control.sample(nsamples)[0],
            experimental.sample(nsamples)[0],
            kind='hex',
            stat_func=None) 
Example #7
Source File: msm.py    From msmexplorer with MIT License 5 votes vote down vote up
def plot_pop_resids(msm, **kwargs):
    """
    Plot residuals between MSM populations and raw counts.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    **kwargs : dict, optional
        Extra arguments to pass to seaborn.jointplot

    Returns
    -------
    ax : matplotlib axis
        matplotlib figure axis

    """
    if hasattr(msm, 'all_populations_'):
        msm_pop = msm.populations_.mean(0)
    elif hasattr(msm, 'populations_'):
        msm_pop = msm.populations_

    raw_pop = msm.countsmat_.sum(1) / msm.countsmat_.sum()
    ax = sns.jointplot(np.log10(raw_pop), np.log10(msm_pop), kind='resid',
                       **kwargs)
    ax.ax_joint.set_xlabel('Raw Populations', size=20)
    ax.ax_joint.set_ylabel('Residuals', size=20)

    return ax 
Example #8
Source File: c5.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def sample_54_1():
    """
    5.4 使用seaborn可视化数据
    :return:
    """
    sns.distplot(tsla_df['p_change'], bins=80)
    plt.show()

    sns.boxplot(x='date_week', y='p_change', data=tsla_df)
    plt.show()

    sns.jointplot(tsla_df['high'], tsla_df['low'])
    plt.show() 
Example #9
Source File: plotting.py    From MJHMC with GNU General Public License v2.0 5 votes vote down vote up
def hist_2d(distr, nsamples, **kwargs):
    """
    Plots a 2d hexbinned histogram of distribution

    Args:
     distr: Distribution object
     nsamples: number of samples to use to generate plot
    """
    sampler = MarkovJumpHMC(distribution=distr, **kwargs)
    samples = sampler.sample(nsamples)

    with sns.axes_style("white"):
       g =  sns.jointplot(samples[0], samples[1], kind='kde', stat_func=None)
    return g 
Example #10
Source File: analysis.py    From cryodrgn with GNU General Public License v3.0 5 votes vote down vote up
def plot_euler(theta,phi,psi,plot_psi=True):
    sns.jointplot(theta,phi,kind='hex',
              xlim=(-180,180),
              ylim=(0,180)).set_axis_labels("theta", "phi")
    if plot_psi:
        plt.figure()
        plt.hist(psi)
        plt.xlabel('psi') 
Example #11
Source File: document.py    From DQLearning-Toolbox with MIT License 5 votes vote down vote up
def saveMovg(df,step=12):
    moving_avg = pd.rolling_mean(df['dsc_log'], step)
    sns.jointplot(x=df['time'],y=moving_avg,color='red')
    plt.title('Moving Average')
    plt.savefig(ma_path)

# 创建word文档 
Example #12
Source File: sim_eval.py    From Conditional_Density_Estimation with MIT License 5 votes vote down vote up
def eval1():
  n_observations = 2000  # number of data points
  n_features = 1  # number of features

  X_train, X_test, y_train, y_test = build_econ1_dataset(n_observations)
  print("Size of features in training data: {}".format(X_train.shape))
  print("Size of output in training data: {}".format(y_train.shape))
  print("Size of features in test data: {}".format(X_test.shape))
  print("Size of output in test data: {}".format(y_test.shape))

  fig, ax = plt.subplots()
  fig.set_size_inches(10, 8)
  sns.regplot(X_train, y_train, fit_reg=False)
  # plt.savefig('toydata.png')
  # plt.show()
  # plot.figure.size = 100
  # plt.show()

  kmn = KernelMixtureNetwork(train_scales=True, n_centers=20)
  kmn.fit(X_train, y_train, n_epoch=300, eval_set=(X_test, y_test))
  kmn.plot_loss()
  # plt.savefig('trainplot.png')
  samples = kmn.sample(X_test)
  print(X_test.shape, samples.shape)
  jp = sns.jointplot(X_test.ravel(), samples, kind="hex", stat_func=None, size=10)
  jp.ax_joint.add_line(Line2D([X_test[0][0], X_test[0][0]], [-40, 40], linewidth=3))
  jp.ax_joint.add_line(Line2D([X_test[1][0], X_test[1][0]], [-40, 40], color='g', linewidth=3))
  jp.ax_joint.add_line(Line2D([X_test[2][0], X_test[2][0]], [-40, 40], color='r', linewidth=3))
  plt.savefig('hexplot.png')
  plt.show()
  d = kmn.predict_density(X_test[0:3, :].reshape(-1, 1), resolution=1000)
  df = pd.DataFrame(d).transpose()
  df.index = np.linspace(kmn.y_min, kmn.y_max, num=1000)
  df.plot(legend=False, linewidth=3, figsize=(12.2, 8))
  plt.savefig('conditional_density.png') 
Example #13
Source File: typeI_analysis.py    From SAMPL6 with MIT License 5 votes vote down vote up
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
    # Extract only pKa values.
    data = data[[x, y]]

    # Find extreme values to make axes equal.
    min_limit = np.ceil(min(data.min()) - 2)
    max_limit = np.floor(max(data.max()) + 2)
    axes_limits = np.array([min_limit, max_limit])

    if kind == 'joint':
        grid = sns.jointplot(x=x, y=y, data=data,
                             kind='reg', joint_kws={'ci': None}, stat_func=None,
                             xlim=axes_limits, ylim=axes_limits, color=color)
        ax = grid.ax_joint
        grid.fig.subplots_adjust(top=0.95)
        grid.fig.suptitle(title)
    elif kind == 'reg':
        ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
        ax.set_title(title)

    # Add diagonal line.
    ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)

    # Add shaded area for 0.5-1 pKa error.
    palette = sns.color_palette('BuGn_r')
    ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
    ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3]) 
Example #14
Source File: typeIII_analysis.py    From SAMPL6 with MIT License 5 votes vote down vote up
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
    # Extract only pKa values.
    data = data[[x, y]]

    # Find extreme values to make axes equal.
    min_limit = np.ceil(min(data.min()) - 2)
    max_limit = np.floor(max(data.max()) + 2)
    axes_limits = np.array([min_limit, max_limit])

    if kind == 'joint':
        grid = sns.jointplot(x=x, y=y, data=data,
                             kind='reg', joint_kws={'ci': None}, stat_func=None,
                             xlim=axes_limits, ylim=axes_limits, color=color)
        ax = grid.ax_joint
        grid.fig.subplots_adjust(top=0.95)
        grid.fig.suptitle(title)
    elif kind == 'reg':
        ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
        ax.set_title(title)

    # Add diagonal line.
    ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)

    # Add shaded area for 0.5-1 pKa error.
    palette = sns.color_palette('BuGn_r')
    ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
    ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3]) 
Example #15
Source File: logP_analysis.py    From SAMPL6 with MIT License 5 votes vote down vote up
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
    # Extract only logP values.
    data = data[[x, y]]

    # Find extreme values to make axes equal.
    min_limit = np.ceil(min(data.min()) - 1)
    max_limit = np.floor(max(data.max()) + 1)
    axes_limits = np.array([min_limit, max_limit])

    if kind == 'joint':
        grid = sns.jointplot(x=x, y=y, data=data,
                             kind='reg', joint_kws={'ci': None}, stat_func=None,
                             xlim=axes_limits, ylim=axes_limits, color=color)
        ax = grid.ax_joint
        grid.fig.subplots_adjust(top=0.95)
        grid.fig.suptitle(title)
    elif kind == 'reg':
        ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
        ax.set_title(title)

    # Add diagonal line.
    ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)

    # Add shaded area for 0.5-1 logP error.
    palette = sns.color_palette('BuGn_r')
    ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
    ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3]) 
Example #16
Source File: logP_analysis.py    From SAMPL6 with MIT License 5 votes vote down vote up
def plot_correlation(x, y, data, title=None, color=None, kind='joint', ax=None):
    # Extract only logP values.
    data = data[[x, y]]

    # Find extreme values to make axes equal.
    min_limit = np.ceil(min(data.min()) - 1)
    max_limit = np.floor(max(data.max()) + 1)
    axes_limits = np.array([min_limit, max_limit])

    if kind == 'joint':
        grid = sns.jointplot(x=x, y=y, data=data,
                             kind='reg', joint_kws={'ci': None}, stat_func=None,
                             xlim=axes_limits, ylim=axes_limits, color=color)
        ax = grid.ax_joint
        grid.fig.subplots_adjust(top=0.95)
        grid.fig.suptitle(title)
    elif kind == 'reg':
        ax = sns.regplot(x=x, y=y, data=data, color=color, ax=ax)
        ax.set_title(title)

    # Add diagonal line.
    ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.7)

    # Add shaded area for 0.5-1 logP error.
    palette = sns.color_palette('BuGn_r')
    ax.fill_between(axes_limits, axes_limits - 0.5, axes_limits + 0.5, alpha=0.2, color=palette[2])
    ax.fill_between(axes_limits, axes_limits - 1, axes_limits + 1, alpha=0.2, color=palette[3]) 
Example #17
Source File: evaluation.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_trajectories(rewards, health, figure_file_obj):
  plt.figure()
  g = sns.jointplot(x=rewards, y=health, kind='kde')
  g.plot_joint(plt.scatter, c='grey', s=30, linewidth=1, marker='+')
  g.ax_joint.collections[0].set_alpha(0)
  g.set_axis_labels('$Reward$', '$Health$')
  if figure_file_obj:
    plt.savefig(figure_file_obj, format='png')
  else:
    plt.show() 
Example #18
Source File: submission.py    From SAMPL6 with MIT License 4 votes vote down vote up
def plot_correlation(x, y, data, title=None, color=None, shaded_area_color=None, hue=None, ax=None):
    import seaborn as sns
    from matplotlib import pyplot as plt

    # Extract only free energies.
    values = data[[x, y]]

    # Find extreme values to make axes equal.
    # Generally plot between -20 and 0, and then
    # set it to the next number divisible by 5.
    min_limit = min(-20, np.floor(min(values.min())/5) * 5)
    max_limit = max(0, np.ceil(max(values.max())/5) * 5)
    axes_limits = np.array([min_limit, max_limit])

    if hue is None:
        grid = sns.jointplot(x=x, y=y, data=data,
                             kind='reg', joint_kws={'ci': None}, stat_func=None,
                             xlim=axes_limits, ylim=axes_limits, color=color)
        ax = grid.ax_joint
        grid.fig.subplots_adjust(top=0.95)
        grid.fig.suptitle(title)
    else:
        unique_hues = sorted(data[hue].unique())
        if ax is None:
            fig, ax = plt.subplots()
        # Set axes limits and ratio.
        ax.set_xlim(axes_limits)
        ax.set_ylim(axes_limits)
        ax.set_aspect('equal', 'box')
        # If a single color is passed, transform it into a palette.
        if not isinstance(color, list):
            color = [color for _ in range(len(unique_hues)+1)]
        # Add regression line single hue and all.
        for value, c in zip(unique_hues, color):
            sns.regplot(x=x, y=y, data=data[data[hue] == value], ci=0, label=value,
                        scatter=True, color=c, line_kws={'alpha': 0.5}, ax=ax)
        # Plot regression line for all the hues together.
        sns.regplot(x=x, y=y, data=data, ci=0, label='All',
                    scatter=False, color=color[len(unique_hues)],
                    line_kws={'alpha': 0.7}, ax=ax)
        ax.legend(loc='upper left')
        ax.set_title(title)

    # Add diagonal line.
    ax.plot(axes_limits, axes_limits, ls='--', c='black', alpha=0.8, lw=0.8)

    # Add shaded area for 1.5 kcal/mol error.
    if shaded_area_color is None:
        shaded_area_color = sns.color_palette('BuGn_r')[2]
    ax.fill_between(axes_limits, axes_limits - 1.5, axes_limits + 1.5, alpha=0.3,
                    color=shaded_area_color)


# =============================================================================
# MAIN SAMPL SUBMISSION CLASS
# ============================================================================= 
Example #19
Source File: plot_z2.py    From cryodrgn with GNU General Public License v3.0 4 votes vote down vote up
def main(args):
    np.random.seed(args.seed)
    f = args.input
    print(f)
    x = pickle.load(open(f,'rb'))
    if args.stride:
        x = x[::args.stride]
    print(x.shape)

    # seaborn jointpoint
    if args.kde:
        g = sns.jointplot(x[:,0],x[:,1], kind='kde')
        ax = g.ax_joint 

    # scatter plot
    else:
        fig,ax = plt.subplots()
        if args.color:
            plt.scatter(x[:,0], x[:,1], c=np.arange(len(x[:,0])), label=f, alpha=args.alpha, s=args.ms, cmap='hsv')
        else:
            plt.scatter(x[:,0], x[:,1], label=f, alpha=args.alpha, s=args.ms)
        plt.xlabel('z1')
        plt.ylabel('z2')
        plt.legend(loc='best')

    if args.sample1:
        ii = np.random.choice(len(x), args.sample1)
        print(ii)
        xd = x[ii]
        print(xd)
        plt.scatter(xd[:,0],xd[:,1],c=np.arange(len(xd)),cmap='hsv')
        if args.annotate:
            for i in range(args.sample1):
                ax.annotate(str(i), xd[i])
    if args.sample2:
        xsplit = np.array_split(x,args.sample2)
        xd = np.array([np.median(xs,axis=0) for xs in xsplit])
        print(len(xd))
        print(xd)
        plt.scatter(xd[:,0],xd[:,1],c='k')#np.arange(len(xd)),cmap='hsv')
    if args.out_s:
        np.savetxt(args.out_s, xd)
    if args.out_png: 
        plt.savefig(args.out_png)
    else:
        plt.show() 
Example #20
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 
Example #21
Source File: distanceWeightCalculation_raster2Polygon.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def visualisationDF(df):    
    dataFrameInfoPrint(df)
    #graph-01
    # df['shapelyArea'].plot.hist(alpha=0.5)    
    #graph-02
    # df['shapelyArea'].plot.kde()    
    #graph-03
    # df[['shapelyLength','shapeIdx']].plot.scatter('shapelyLength','shapeIdx')    
    #normalize data in a range of columns
    cols_to_norm=['shapeIdx', 'FRAC']
    df[cols_to_norm]=df[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
    
    a='shapeIdx'
    b='FRAC'
    c='park_class'
    
    #graph-04
    # sns.jointplot(a,b,df,kind='hex')
    
    #graph-05
    # sns.jointplot(a, b, df, kind='kde')
    
    #graph-06
    # sns.catplot(x='park_class',y=a,data=df)
    
    #graph-07
    '''
    # Initialize the figure
    f, ax = plt.subplots()
    sns.despine(bottom=True, left=True)
    # Show each observation with a scatterplot
    sns.stripplot(x=a, y=c, hue=c,data=df, dodge=True, alpha=.25, zorder=1)    
    # Show the conditional means
    sns.pointplot(x=a, y=c, hue=c,data=df, dodge=.532, join=False, palette="dark",markers="d", scale=.75, ci=None)
    # Improve the legend 
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[3:], labels[3:], title=b,handletextpad=0, columnspacing=1,loc="lower right", ncol=3, frameon=True)
    '''
    
    #graph-08
    # sns.catplot(x=c,y=a,data=df,kind='box')
    
    #graph-09
    # sns.catplot(x=c,y=a,data=df,kind='violin')
    
    #graph-10
    '''
    f, axs = plt.subplots(1, 2, figsize=(12, 6))
    # First axis    
    df[b].plot.hist(ax=axs[0])
    # Second axis
    df[b].plot.kde(ax=axs[1])
    # Title
    f.suptitle(b)
    # Display
    plt.show()
    '''        

#从新定义栅格投影,参考投影为vector .shp文件 
Example #22
Source File: action.py    From insightconnect-plugins with MIT License 4 votes vote down vote up
def run(self, params={}):
        # Set styles
        sns.set_palette(params.get('color_palette'))
        sns.set(style=params.get('margin_style'))

        # Process the data and create the plot
        try:
            decoded_data = base64.b64decode(params.get('csv_data'))
        except Exception as e:
            error = f"Failed to decode base64 encoded CSV data with error: {e}"
            self.logger.error(error)
            raise e

        df = pd.read_csv(BytesIO(decoded_data))
        x = params.get('x_value')
        y = params.get('y_value')
        kind = params.get('kind')

        args = {
            "data": df,
            "x": x,
            "y": y,
            "kind": kind
        }

        if not x or (x not in df):
            error = f"Column for X value({x}) not in data set, cannot create plot..."
            self.logger.error(error)
            return Exception(error)
        elif not y or (y not in df):
            error = f"Column for Y value ({y}) not in data set, cannot create plot..."
            self.logger.error(error)
            return Exception(error)

        # JointPlots have the savefig method, call it directly
        self.logger.info("Creating plot...")
        plot = sns.jointplot(**args)

        # bbox_inches is required to ensure that labels are cut off
        plot.savefig('plot.png', bbox_inches='tight')
        with open('plot.png', 'rb', )as f:
            plot = base64.b64encode(f.read())

        return {
            "csv": params.get('csv_data'),
            "plot": plot.decode('utf-8')
        }