Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a black frame around a colorbar

I have created a heatmap and a colorbar in two separate axes. I want to create a black frame around each of the plots. I've succeeded in ax0 (the heatmap) but for ax1 (the colorbar) it doesn't work. See picture:

enter image description here

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

df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10, len(df) / 5.2), gridspec_kw={'width_ratios': [15, 15]})
sns.heatmap(df, annot=False, cmap='RdYlGn', cbar_ax=ax1, ax=ax0)
for _, spine in ax1.spines.items():
    spine.set_visible(True)
for _, spine in ax0.spines.items():
    spine.set_visible(True)
like image 836
Amit V Avatar asked Dec 05 '25 20:12

Amit V


1 Answers

Seaborn, by default, sets the outline line width of the colour bar to zero1.

You can set the line width (lw) and edge colour for all the spines in each ax like so:

fig, (ax0, ax1) = plt.subplots(ncols=2)
sns.heatmap(df, annot=False, cmap="RdYlGn", cbar_ax=ax1, ax=ax0)

for spine in ax0.spines.values():
    spine.set_visible(True)
for spine in ax1.spines.values():
    spine.set(visible=True, lw=.8, edgecolor="black")

Which produces:

enter image description here

The colour bar also has an outline spine so ax1 could just be done with just this line.

ax1.spines["outline"].set(visible=True, lw=.8, edgecolor="black")
like image 121
Alex Avatar answered Dec 08 '25 12:12

Alex