I have a basic heatmap created using the seaborn
library, and want to move the colorbar from the default, vertical and on the right, to a horizontal one above the heatmap. How can I do this?
Here's some sample data and an example of the default:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# Create data
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])
# Default heatma
ax = sns.heatmap(df)
plt.show()
You have to use axes divider to put colorbar on top of a seaborn figure. Look for the comments.
For more info read this official example of matplotlib: https://matplotlib.org/gallery/axes_grid1/demo_colorbar_with_axes_divider.html?highlight=demo%20colorbar%20axes%20divider
Heatmap argument like
sns.heatmap(df, cbar_kws = {'orientation':'horizontal'})
is useless because it put colorbar on bottom position.I would like to show example with subplots which allows to control size of plot to preserve square geometry of heatmap. This example is very short:
Looking at the documentation we find an argument
cbar_kws
. This allows to specify argument passed on to matplotlib'sfig.colorbar
method.So we can use any of the possible arguments to
fig.colorbar
, providing a dictionary tocbar_kws
.In this case you need
location="top"
to place the colorbar on top. Becausecolorbar
by default positions the colorbar using a gridspec, which then does not allow for the location to be set, we need to turn that gridspec off (use_gridspec=False
).Complete example: