heatmap-like plot, but for categorical variables in seaborn

前端 未结 2 1826
暗喜
暗喜 2020-12-18 21:50

Same question as heatmap-like plot, but for categorical variables but using python and seaborn instead of R:

Imagine I have the following dataframe:

         


        
相关标签:
2条回答
  • 2020-12-18 22:09

    I would probably use bokeh for this purpose as it has categorical heatmaps built in. Y-axis labels are written horizontally too, which is more readable.

    http://docs.bokeh.org/en/0.11.1/docs/gallery/heatmap_chart.html

    0 讨论(0)
  • 2020-12-18 22:20

    You can use a discrete colormap and modify the colorbar, instead of using a legend.

    value_to_int = {j:i for i,j in enumerate(pd.unique(df.values.ravel()))} # like you did
    n = len(value_to_int)     
    # discrete colormap (n samples from a given cmap)
    cmap = sns.color_palette("Pastel2", n) 
    ax = sns.heatmap(df.replace(value_to_int), cmap=cmap) 
    # modify colorbar:
    colorbar = ax.collections[0].colorbar 
    r = colorbar.vmax - colorbar.vmin 
    colorbar.set_ticks([colorbar.vmin + r / n * (0.5 + i) for i in range(n)])
    colorbar.set_ticklabels(list(value_to_int.keys()))                                          
    plt.show()
    

    The colorbar part is adapted from this answer

    HTH

    0 讨论(0)
提交回复
热议问题