Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the height of a Seaborn heatmap colorbar

I have the following Python code to create a heatmap using the Seaborn package:

f, ax = plt.subplots(figsize=(21,5))
heatmap = sns.heatmap(significantBig5[basic].as_matrix().T,mask=labelsDf.T,
     annot=False,fmt='.2f',yticklabels=basic_labels,linewidths=0.5,square=True,
     xticklabels=traits)
plt.xticks(rotation=70)

This creates the following heatmap: sample heatmap

I would like to format this heatmap so that the colorbar on the right side is shorter. Is there a way to do this?

like image 931
sealonging314 Avatar asked Nov 28 '16 16:11

sealonging314


People also ask

What is FMT in heatmap?

cmap: The mapping from data values to color space. center: The value at which to center the colormap when plotting divergent data. annot: If True, write the data value in each cell. fmt: String formatting code to use when adding annotations. linewidths: Width of the lines that will divide each cell.


2 Answers

You can also use the extra keyword arguments for the sns heatmap colorbar the cbar_kws. They modify the settings for the matplotlib colorbar documented here

Using the code of @Serenity with the shrinkage keyword we get this:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

arr = np.random.random((1,9))
df = pd.DataFrame(arr)
sns.heatmap(arr,cbar=True,cbar_kws={"shrink": .82})

plt.show()

enter image description here

like image 135
Reed Richards Avatar answered Oct 09 '22 15:10

Reed Richards


Use cbar_ax argument and set position of color bar you like:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

arr = np.random.random((1,9))
df = pd.DataFrame(arr)
fig, ax = plt.subplots(1, 1)
cbar_ax = fig.add_axes([.905, .3, .05, .3])
sns.heatmap(arr, ax=ax, cbar_ax = cbar_ax, cbar=True)

plt.show()

enter image description here

like image 40
Serenity Avatar answered Oct 09 '22 15:10

Serenity