Python seaborn.diverging_palette() Examples

The following are 11 code examples of seaborn.diverging_palette(). 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: atoms.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #2
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 5 votes vote down vote up
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();
############################################################################################## 
Example #3
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 5 votes vote down vote up
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();
############################################################################################## 
Example #4
Source File: plotting.py    From astrocats with MIT License 5 votes vote down vote up
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)) 
Example #5
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 4 votes vote down vote up
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();
################################################################################# 
Example #6
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 4 votes vote down vote up
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();
################################################################################# 
Example #7
Source File: misc.py    From mriqc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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 
Example #8
Source File: contrasts.py    From fitlins with Apache License 2.0 4 votes vote down vote up
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 
Example #9
Source File: get_contact_trace.py    From getcontacts with Apache License 2.0 4 votes vote down vote up
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) 
Example #10
Source File: get_contact_trace.py    From getcontacts with Apache License 2.0 4 votes vote down vote up
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) 
Example #11
Source File: showMatLabFig._spatioTemporal.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
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