Discrete legend in seaborn heatmap plot

后端 未结 4 632
不知归路
不知归路 2020-12-09 09:38

I am using the data present here to construct this heat map using seaborn and pandas.

Code:

    import pandas
    import seaborn.apionly as sns

             


        
4条回答
  •  盖世英雄少女心
    2020-12-09 10:14

    I find that a discretized colorbar in seaborn is much easier to create if you use a ListedColormap. There's no need to define your own functions, just add a few lines to basically customize your axes.

    import pandas
    import matplotlib.pyplot as plt
    import seaborn as sns
    from matplotlib.colors import ListedColormap
    
    
    # Read in csv file
    df_trans = pandas.read_csv('LUH2_trans_matrix.csv')
    
    sns.set(font_scale=0.8)
    # cmap is now a list of colors
    cmap = sns.cubehelix_palette(start=2.8, rot=.1, light=0.9, n_colors=3)
    df_trans = df_trans.set_index(['Unnamed: 0'])
    
    # Create two appropriately sized subplots
    grid_kws = {'width_ratios': (0.9, 0.03), 'wspace': 0.18}
    fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw=grid_kws)
    
    ax = sns.heatmap(df_trans, ax=ax, cbar_ax=cbar_ax, cmap=ListedColormap(cmap),
                     linewidths=.5, linecolor='lightgray',
                     cbar_kws={'orientation': 'vertical'})
    
    # Customize tick marks and positions
    cbar_ax.set_yticklabels(['B', 'A', 'C'])
    cbar_ax.yaxis.set_ticks([ 0.16666667, 0.5, 0.83333333])
    
    
    # X - Y axis labels
    ax.set_ylabel('FROM')
    ax.set_xlabel('TO')
    
    # Rotate tick labels
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=0)
    locs, labels = plt.yticks()
    plt.setp(labels, rotation=0)
    

提交回复
热议问题