Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the rotation of tick labels in Seaborn heatmap

I'm plotting a heatmap in Seaborn. The problem is that I have too many squares in my plot so the x and y labels are too close to each other to be useful. So I'm creating a list of xticks and yticks to use. However passing this list to the function rotates the labels in the plot. It would be really nice to have seaborn automatically drop some of the ticks, but barring that I would like to be able to have the yticks upright.

import pandas as pd import numpy as np import seaborn as sns  data = pd.DataFrame(np.random.normal(size=40*40).reshape(40,40))  yticks = data.index keptticks = yticks[::int(len(yticks)/10)] yticks = ['' for y in yticks] yticks[::int(len(yticks)/10)] = keptticks  xticks = data.columns keptticks = xticks[::int(len(xticks)/10)] xticks = ['' for y in xticks] xticks[::int(len(xticks)/10)] = keptticks  sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks) 

enter image description here

like image 522
Artturi Björk Avatar asked Nov 20 '14 10:11

Artturi Björk


People also ask

How do I rotate a tick label?

Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax. set_xticklabels() and ax.


2 Answers

seaborn uses matplotlib internally, as such you can use matplotlib functions to modify your plots. I've modified the code below to use the plt.yticks function to set rotation=0 which fixes the issue.

import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns   data = pd.DataFrame(np.random.normal(size=40*40).reshape(40,40))  yticks = data.index keptticks = yticks[::int(len(yticks)/10)] yticks = ['' for y in yticks] yticks[::int(len(yticks)/10)] = keptticks  xticks = data.columns keptticks = xticks[::int(len(xticks)/10)] xticks = ['' for y in xticks] xticks[::int(len(xticks)/10)] = keptticks  sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)  # This sets the yticks "upright" with 0, as opposed to sideways with 90. plt.yticks(rotation=0)   plt.show() 

Plot

like image 145
Ffisegydd Avatar answered Sep 21 '22 17:09

Ffisegydd


You can also call the methods of heatmap object:

    g = sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)     g.set_yticklabels(g.get_yticklabels(), rotation = 0, fontsize = 8) 

I am not sure why this isn't in the documentation for sns.heatmap, but the same methods are described here: http://seaborn.pydata.org/generated/seaborn.FacetGrid.html

I believe these methods are available to every seaborn plot object but couldn't find a general API for that.

like image 43
Ryszard Cetnarski Avatar answered Sep 24 '22 17:09

Ryszard Cetnarski