0

I have the next code:

heatmap = sns.clustermap(corrMatrix, row_colors=row_colors, 
                         #metric='correlation',
                         #method='single',
                         xticklabels=True, yticklabels=True, 
                         cmap='coolwarm', annot=False, fmt=".2f", 
                         #annot_kws={'size':6}, square=False,
                         dendrogram_ratio=(.1, .2),
                         cbar_pos=(1, .2, .03, .4))

loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=90)
heatmap.set_yticklabels(labels, rotation=0)
bottom, top = heatmap.get_ylim()
heatmap.set_ylim(bottom + 0.5, top -0.5)

heatmap.savefig(r'similarity' + '.svg', format='svg', dpi=600, bbox_inches = "tight" )

Works good but doesnt save the figure, only with this type of plot (clustermap) i was trying with plt.savefig() and figure = heatmap.get_figure() and nothing

Samael Olascoaga
  • 161
  • 2
  • 10

1 Answers1

1

Your code crashing on the line heatmap.set_xticklabels(...) with

AttributeError: 'ClusterGrid' object has no attribute 'set_xticklabels'

sns.clustermap is a figure-level function. It returns a ClusterGrid (axes-level functions return a matplotlib ax).

In seaborn's documentation, it is custom to call the return value of a figure-level function g = (with g being the first letter of 'grid'). If you start giving these variables very different names, it is easy to get lost in seaborn's documentation, and also when trying to use matplotlib functions for further customization.

The following code shows the intended naming conventions and the intended way to rotate the labels. (I don't understand the changing the ylims, maybe this is related to an old problem with matplotlib? Changing the ylims this way makes the plot look wrong.)

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

g = sns.clustermap(np.random.rand(10, 10), row_colors=plt.cm.tab10.colors,
                   xticklabels=True, yticklabels=True,
                   cmap='coolwarm', annot=False, fmt=".2f",
                   dendrogram_ratio=(.1, .2),
                   cbar_pos=(1, .2, .03, .4))

g.ax_heatmap.tick_params(axis='x', rotation=90)
g.ax_heatmap.tick_params(axis='y', rotation=0)
# labels = g.ax_heatmap.get_xticklabels()
# g.ax_heatmap.set_xticklabels(labels, rotation=90)
# g.ax_heatmap.set_yticklabels(labels, rotation=0)
# bottom, top = g.ax_heatmap.get_ylim()
# g.ax_heatmap.set_ylim(bottom + 0.5, top - 0.5)

g.fig.savefig(r'similarity' + '.svg', format='svg', dpi=600, bbox_inches="tight")
JohanC
  • 71,591
  • 8
  • 33
  • 66