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:

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)
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:

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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With