當前位置: 首頁>>代碼示例>>Python>>正文


Python seaborn.diverging_palette方法代碼示例

本文整理匯總了Python中seaborn.diverging_palette方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.diverging_palette方法的具體用法?Python seaborn.diverging_palette怎麽用?Python seaborn.diverging_palette使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在seaborn的用法示例。


在下文中一共展示了seaborn.diverging_palette方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _scalars_to_hex_colors

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def _scalars_to_hex_colors(scalar_field, start=None, end=None, cmap=None):
        """
        Convert scalar values to hex codes using a colormap.

        Args:
            scalar_field (numpy.ndarray/list): Scalars to convert.
            start (float): Scalar value to map to the bottom of the colormap (values below are clipped). (Default is
                None, use the minimal scalar value.)
            end (float): Scalar value to map to the top of the colormap (values above are clipped).  (Default is
                None, use the maximal scalar value.)
            cmap (matplotlib.cm): The colormap to use. (Default is None, which gives a blue-red divergent map.)

        Returns:
            (list): The corresponding hex codes for each scalar value passed in.
        """
        if start is None:
            start = np.amin(scalar_field)
        if end is None:
            end = np.amax(scalar_field)
        interp = interp1d([start, end], [0, 1])
        remapped_field = interp(
            np.clip(scalar_field, start, end)
        )  # Map field onto [0,1]

        if cmap is None:
            try:
                from seaborn import diverging_palette
            except ImportError:
                print(
                    "The package seaborn needs to be installed for the plot3d() function!"
                )
            cmap = diverging_palette(245, 15, as_cmap=True)  # A nice blue-red palette

        return [
            rgb2hex(cmap(scalar)[:3]) for scalar in remapped_field
        ]  # The slice gets RGB but leaves alpha 
開發者ID:pyiron,項目名稱:pyiron,代碼行數:38,代碼來源:atoms.py

示例2: plot_confusion_matrix

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def plot_confusion_matrix(y_test,y_pred, model_name='Model'):
    """
    This plots a beautiful confusion matrix based on input: ground truths and predictions
    """
    #Confusion Matrix
    '''Plotting CONFUSION MATRIX'''
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_style('darkgrid')

    '''Display'''
    from IPython.core.display import display, HTML
    display(HTML("<style>.container { width:95% !important; }</style>"))
    pd.options.display.float_format = '{:,.2f}'.format

    #Get the confusion matrix and put it into a df
    from sklearn.metrics import confusion_matrix, f1_score

    cm = confusion_matrix(y_test, y_pred)

    cm_df = pd.DataFrame(cm,
                         index = np.unique(y_test).tolist(),
                         columns = np.unique(y_test).tolist(),
                        )

    #Plot the heatmap
    plt.figure(figsize=(12, 8))

    sns.heatmap(cm_df,
                center=0,
                cmap=sns.diverging_palette(220, 15, as_cmap=True),
                annot=True,
                fmt='g')

    plt.title(' %s \nF1 Score(avg = micro): %0.2f \nF1 Score(avg = macro): %0.2f' %(
        model_name,f1_score(y_test, y_pred, average='micro'),f1_score(y_test, y_pred, average='macro')),
              fontsize = 13)
    plt.ylabel('True label', fontsize = 13)
    plt.xlabel('Predicted label', fontsize = 13)
    plt.show();
############################################################################################## 
開發者ID:AutoViML,項目名稱:Auto_ViML,代碼行數:43,代碼來源:Auto_NLP.py

示例3: radiocolorf

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def radiocolorf(freq):
    ffreq = (float(freq) - 1.0)/(45.0 - 1.0)
    pal = sns.diverging_palette(200, 60, l=80, as_cmap=True, center="dark")
    return rgb2hex(pal(ffreq)) 
開發者ID:astrocatalogs,項目名稱:astrocats,代碼行數:6,代碼來源:plotting.py

示例4: plot_classification_matrix

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def plot_classification_matrix(y_test, y_pred, model_name='Model'):
    """
    This plots a beautiful classification report based on 2 inputs: ground truths and predictions
    """
    # Classification Matrix
    '''Plotting CLASSIFICATION MATRIX'''
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_style('darkgrid')

    '''Display'''
    from IPython.core.display import display, HTML
    display(HTML("<style>.container { width:95% !important; }</style>"))
    pd.options.display.float_format = '{:,.2f}'.format

    #Get the confusion matrix and put it into a df
    from sklearn.metrics import precision_score
    from sklearn.metrics import classification_report
    from sklearn.metrics import precision_score

    cm = classification_report(y_test, y_pred,output_dict=True)

    cm_df = pd.DataFrame(cm)

    #Plot the heatmap
    plt.figure(figsize=(12, 8))

    sns.heatmap(cm_df,
                center=0,
                cmap=sns.diverging_palette(220, 15, as_cmap=True),
                annot=True,
                fmt='0.2f')

    plt.title(""" %s
    \nAverage Precision Score(avg = micro): %0.2f \nAverage Precision Score(avg = macro): %0.2f""" %(
        model_name, precision_score(y_test,y_pred, average='micro'),
        precision_score(y_test, y_pred, average='macro')),
              fontsize = 13)
    plt.ylabel('True label', fontsize = 13)
    plt.xlabel('Predicted label', fontsize = 13)
    plt.show();
################################################################################# 
開發者ID:AutoViML,項目名稱:Auto_ViML,代碼行數:44,代碼來源:Auto_NLP.py

示例5: plot_corrmat

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def plot_corrmat(in_csv, out_file=None):
    import seaborn as sn

    sn.set(style="whitegrid")

    dataframe = pd.read_csv(in_csv, index_col=False, na_values="n/a", na_filter=False)
    colnames = dataframe.columns.ravel().tolist()

    for col in ["subject_id", "site", "modality"]:
        try:
            colnames.remove(col)
        except ValueError:
            pass

    # Correlation matrix
    corr = dataframe[colnames].corr()
    corr = corr.dropna((0, 1), "all")

    # Generate a mask for the upper triangle
    mask = np.zeros_like(corr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    # Generate a custom diverging colormap
    cmap = sn.diverging_palette(220, 10, as_cmap=True)

    # Draw the heatmap with the mask and correct aspect ratio
    corrplot = sn.clustermap(
        corr, cmap=cmap, center=0.0, method="average", square=True, linewidths=0.5
    )
    plt.setp(corrplot.ax_heatmap.yaxis.get_ticklabels(), rotation="horizontal")
    # , mask=mask, square=True, linewidths=.5, cbar_kws={"shrink": .5})

    if out_file is None:
        out_file = "corr_matrix.svg"

    fname, ext = op.splitext(out_file)
    if ext[1:] not in ["pdf", "svg", "png"]:
        ext = ".svg"
        out_file = fname + ".svg"

    corrplot.savefig(
        out_file, format=ext[1:], bbox_inches="tight", pad_inches=0, dpi=100
    )
    return corrplot 
開發者ID:poldracklab,項目名稱:mriqc,代碼行數:46,代碼來源:misc.py

示例6: plot_contrast_matrix

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def plot_contrast_matrix(contrast_matrix, ornt='vertical', ax=None):
    """ Plot correlation matrix

    Parameters
    ----------
    mat : DataFrame
        Design matrix with columns consisting of explanatory variables followed
        by confounds
    n_evs : int
        Number of explanatory variables to separate from confounds
    partial : {'upper', 'lower', None}, optional
        Plot matrix as upper triangular (default), lower triangular or full

    Returns
    -------
    ax : Axes
        Axes containing plot
    """

    if ax is None:
        plt.figure()
        ax = plt.gca()

    if ornt == 'horizontal':
        contrast_matrix = contrast_matrix.T

    vmax = np.abs(contrast_matrix.values).max()

    # Use a red/blue (+1/-1) diverging colormap
    cmap = sns.diverging_palette(220, 10, as_cmap=True)

    sns.heatmap(contrast_matrix, vmin=-vmax, vmax=vmax, square=True,
                linewidths=0.5, cmap=cmap,
                cbar_kws={'shrink': 0.5, 'orientation': ornt,
                          'ticks': np.linspace(-vmax, vmax, 5)},
                ax=ax)

    # Variables along top and left
    ax.xaxis.tick_top()
    xtl = ax.get_xticklabels()
    ax.set_xticklabels(xtl, rotation=90)

    return ax 
開發者ID:poldracklab,項目名稱:fitlins,代碼行數:45,代碼來源:contrasts.py

示例7: write_correlation

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def write_correlation(contact_frames, labels, output_file):
    # Example adapted from https://seaborn.pydata.org/examples/many_pairwise_correlations.html
    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    # print(contact_frames)

    sns.set(style="white")

    # Convert frames to pandas dataframe (rows are time, cols interactions)
    rows = max(map(max, contact_frames)) + 1
    cols = len(contact_frames)
    d = pd.DataFrame(data=np.zeros(shape=(rows, cols)), columns=labels)
    for i, contacts in enumerate(contact_frames):
        d[labels[i]][contacts] = 1

    # print(d)

    # Compute the correlation matrix
    dmat = d.corr()
    np.fill_diagonal(dmat.values, 0)
    # vmax = max(vmax, -vmin)
    # vmin = min(vmin, -vmax)
    vmax = 1
    vmin = -1
    # print(jac_sim)
    # print(vmin, vmax)

    # Generate a mask for the upper triangle
    mask = np.zeros_like(dmat, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    # Set up the matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))
    # plt.subplots(figsize=(11, 9))

    # Generate a custom diverging colormap
    cmap = sns.diverging_palette(220, 10, as_cmap=True)

    # Draw the heatmap with the mask and correct aspect ratio
    hm = sns.heatmap(dmat, mask=mask, cmap=cmap, vmax=vmax, vmin=vmin, center=0, square=True, linewidths=0)
    # sns.heatmap(corr, mask=mask, cmap=cmap, vmax=, center=0, square=True, linewidths=0, cbar_kws={"shrink": .5})
    f.tight_layout()

    print("Writing correlation matrix to", output_file)
    f.savefig(output_file) 
開發者ID:getcontacts,項目名稱:getcontacts,代碼行數:49,代碼來源:get_contact_trace.py

示例8: write_jaccard

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def write_jaccard(contact_frames, labels, output_file):
    # Example adapted from https://seaborn.pydata.org/examples/many_pairwise_correlations.html
    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    # print(contact_frames)

    sns.set(style="white")

    # Convert frames to pandas dataframe (rows are time, cols interactions)
    rows = max(map(max, contact_frames)) + 1
    cols = len(contact_frames)
    d = pd.DataFrame(data=np.zeros(shape=(rows, cols)), columns=labels)
    for i, contacts in enumerate(contact_frames):
        d[labels[i]][contacts] = 1

    # print(d)

    # Compute the correlation matrix
    from sklearn.metrics.pairwise import pairwise_distances
    jac_sim = 1 - pairwise_distances(d.T, metric="hamming")
    jac_sim = pd.DataFrame(jac_sim, index=d.columns, columns=d.columns)
    np.fill_diagonal(jac_sim.values, 0)
    vmax = max(jac_sim.max())
    vmin = min(jac_sim.min())
    # vmax = max(vmax, -vmin)
    # vmin = min(vmin, -vmax)
    vmax = 1
    vmin = 0
    # print(jac_sim)
    # print(vmin, vmax)

    # Generate a mask for the upper triangle
    mask = np.zeros_like(jac_sim, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True

    # Set up the matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))
    # plt.subplots(figsize=(11, 9))

    # Generate a custom diverging colormap
    cmap = sns.diverging_palette(220, 10, as_cmap=True)

    # Draw the heatmap with the mask and correct aspect ratio
    hm = sns.heatmap(jac_sim, mask=mask, cmap=cmap, vmax=vmax, vmin=vmin, center=0.5, square=True, linewidths=0)
    # sns.heatmap(corr, mask=mask, cmap=cmap, vmax=, center=0, square=True, linewidths=0, cbar_kws={"shrink": .5})
    f.tight_layout()

    print("Writing Jaccard similarity to", output_file)
    f.savefig(output_file) 
開發者ID:getcontacts,項目名稱:getcontacts,代碼行數:53,代碼來源:get_contact_trace.py

示例9: graphMerge

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import diverging_palette [as 別名]
def graphMerge(num_meanDis_DF):
    plt.clf()
    import plotly.express as px
    from plotly.offline import plot
    
    #01-draw scatter paring
    # coore_columns=["number","mean distance","PHMI"]
    # fig = px.scatter_matrix(num_meanDis_DF[coore_columns],width=1800, height=800)
    # # fig.show() #show in jupyter
    # plot(fig)
     
    #02-draw correlation using plt.matshow-A
    # Corrcoef=np.corrcoef(np.array(num_meanDis_DF[coore_columns]).transpose()) #sns_columns=["number","mean distance","PHMI"]
    # print(Corrcoef)
    # plt.matshow(num_meanDis_DF[coore_columns].corr())
    # plt.xticks(range(len(coore_columns)), coore_columns)
    # plt.yticks(range(len(coore_columns)), coore_columns)
    # plt.colorbar()
    # plt.show()    
    
    #03-draw correlation -B
    # Compute the correlation matrix
    # plt.clf()
    # corr_columns_b=["number","mean distance","PHMI"]
    # corr = num_meanDis_DF[corr_columns_b].corr()    
    corr = num_meanDis_DF.corr()  
    # # Generate a mask for the upper triangle
    # mask = np.triu(np.ones_like(corr, dtype=np.bool))    
    # # Set up the matplotlib figure
    # f, ax = plt.subplots(figsize=(11, 9))    
    # # Generate a custom diverging colormap
    # cmap = sns.diverging_palette(220, 10, as_cmap=True)    
    # # Draw the heatmap with the mask and correct aspect ratio
    # sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={"shrink": .5})
    
    #04
    # Draw a heatmap with the numeric values in each cell
    plt.clf()
    sns.set()
    f, ax = plt.subplots(figsize=(15, 13))
    sns.heatmap(corr, annot=True, fmt=".2f", linewidths=.5, ax=ax)
        
    #04-draw curves
    # plt.clf()
    # sns_columns=["number","mean distance","PHMI"]
    # sns.set(rc={'figure.figsize':(25,3)})
    # sns.lineplot(data=num_meanDis_DF[sns_columns], palette="tab10", linewidth=2.5)
   
#rpy2調用R編程,參考:https://rpy2.github.io/doc/v2.9.x/html/introduction.html 
開發者ID:richieBao,項目名稱:python-urbanPlanning,代碼行數:51,代碼來源:showMatLabFig._spatioTemporal.py


注:本文中的seaborn.diverging_palette方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。