Dance Party2
Dance Party2

Reputation: 7536

Seaborn Heatmap Colorbar Label as Percentage

Given this heat map:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)

How would I go about making the color bar values display in percent format? Also, what if I just wanted to show the first and last values on the color bar?

Thanks in advance!

Upvotes: 21

Views: 40089

Answers (4)

Joe Heffer
Joe Heffer

Reputation: 399

You should get the colour bar object and then get the relevant axis object:

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

fig, ax = plt.subplots()
sns.heatmap(df, ax=ax, cbar_kws={'label': 'My Label'})
cbar = ax.collections[0].colorbar
cbar.ax.yaxis.set_major_formatter(PercentFormatter(1, 0))

Upvotes: 10

Alexandre
Alexandre

Reputation: 1285

Well, I had a similar problem and figured out how to properly set a formatter. Your example would become something like:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()

uniform_data = np.random.rand(10, 12)
uniform_data = 100 * uniform_data

sns.heatmap(uniform_data,
            cbar_kws={'format': '%.0f%%'})

So, what you have to do is to pass an old-style string formatter to add percentages to colorbar labels. Not exactly what I would name self-evident, but works...

To show only the first and last, then you add vmax, vmin and an extra parameter to cbar_kws:

sns.heatmap(uniform_data,
            cbar_kws={'format': '%.0f%%', 'ticks': [0, 100]},
            vmax=100,
            vmin=0)

Upvotes: 23

Stefaan
Stefaan

Reputation: 4916

iterating on the solution of @mwaskom, without creating the colorbar yourself:

import numpy as np
import seaborn as sns
data = np.random.rand(8, 12)
ax = sns.heatmap(data, vmin=0, vmax=1)
cbar = ax.collections[0].colorbar
cbar.set_ticks([0, .2, .75, 1])
cbar.set_ticklabels(['low', '20%', '75%', '100%'])

custom seaborn heatmap color bar labels

Upvotes: 41

mwaskom
mwaskom

Reputation: 49002

You need to be able to access the colorbar object. It might be buried in the figure object somewhere, but I couldn't find it, so the easy thing to do is just to make it yourself:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cbar=False, vmin=0, vmax=1)
cbar = ax.figure.colorbar(ax.collections[0])
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["0%", "100%"])

enter image description here

Upvotes: 7

Related Questions