Search code examples
pythonseabornheatmapdendrogram

how to show y axis to clustermap python dendrogram?


I am fighting against python seaborn clustermap. I would like to plot the dendrogram above the heatmap with the y axis visible. Let me try to explain better with this example:

import seaborn as sns
from scipy.cluster import hierarchy
iris = sns.load_dataset("iris")
species = iris.pop("species")
g = sns.clustermap(iris,row_cluster=False,figsize = (18,14),dendrogram_ratio=(.1, .3))
den = hierarchy.dendrogram(g.dendrogram_col.linkage, labels = iris.columns, color_threshold=35,distance_sort=True,ax = g.ax_col_dendrogram) 

clustermap without yaxis

as you can see it shows well the color_threshold with green and blue lines, but it doesn't show the y axis ticks.

If you just call the hierarchy from scipy you would obtain this:

from scipy.cluster import hierarchy
hierarchy.dendrogram(g.dendrogram_col.linkage, labels = iris.columns, color_threshold=35,distance_sort=True) 

you will obtain this figure:

scipy hierarchy with yaxis

does someone have some way to show the y axis on the clustermap dendrogram? Thanks Emanuele Martini


Solution

  • The first change that is needed, is to turn the axis on. Then you need to set a tick locator and formatter. Optionally you set the horizontal grid on, and you can make some of the spines visible.

    Here is some example code:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import ScalarFormatter, MaxNLocator
    import seaborn as sns
    from scipy.cluster import hierarchy
    
    iris = sns.load_dataset("iris")
    species = iris.pop("species")
    g = sns.clustermap(iris, row_cluster=False, figsize=(18, 14), dendrogram_ratio=(.1, .3))
    den = hierarchy.dendrogram(g.dendrogram_col.linkage, labels=iris.columns,
                               color_threshold=35, distance_sort=True, ax=g.ax_col_dendrogram)
    g.ax_col_dendrogram.axis('on')
    # sns.despine(ax=g.ax_col_dendrogram, left=False, right=True, top=True, bottom=True)
    g.ax_col_dendrogram.yaxis.set_major_locator(MaxNLocator())
    g.ax_col_dendrogram.yaxis.set_major_formatter(ScalarFormatter())
    g.ax_col_dendrogram.grid(axis='y', ls='--', color='grey')
    # g.ax_col_dendrogram.yaxis.tick_right()
    plt.show()
    

    clustermap with y-axis