Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secondary x-axis on a seaborn heatmap

I have a following DataFrame (called hehe):

    11  22  33  44  55  66  77
s1  -3  5   7   8   -9  4   7
s2  4   3   8   1   4   4   -12
s3  1   -2  1   -4  8   8   -8
s4  -6  4   -4  9   -4  2   -6

And then the following code:

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(6,4), gridspec_kw={'width_ratios':(1,15)})
sns.heatmap(hehe, ax=ax2, cbar=False, cmap="coolwarm", linewidth=1, vmin=-25, vmax=25)
ax2.set_aspect("equal")
ax2.set_title("A", fontsize=20, pad=30)

plt.colorbar(plt.cm.ScalarMappable(cmap="coolwarm", norm=mpl.colors.Normalize(vmin=-25, vmax=25)), cax=ax1)
ax1.yaxis.set_ticks_position('left')

generates a plot:
enter image description here

I would like to add an additional x-axis to the top of the heatmap that will help me mark columns with a star (for statistical significancy). Let's say it would be: new_annotation = ["","","","","*","*",""]
I do not know how achieve this... I have been playing around with copying axes with twiny() but for some reason it did not work for me: the whole heatmap went out-of-bounds.

like image 469
maciek Avatar asked Jan 18 '26 06:01

maciek


1 Answers

You can do something like this:

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

# hehe = pd.read_clipboard()
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(6,4), gridspec_kw={'width_ratios':(1,15)})
sns.heatmap(hehe, ax=ax2, cbar=False, cmap="coolwarm", linewidth=1, vmin=-25, vmax=25)
# ax2.set_aspect("equal")
ax2.set_title("A", fontsize=20, pad=40)

ax3 = ax2.twiny()
# ax3.set_aspect("equal")
ax3.set_xlim([0,ax2.get_xlim()[1]])
ax3.set_xticks(ax2.get_xticks())
ax3.set_xticklabels(["","","","","*","*",""], fontsize=16)
ax3.tick_params(top=False)
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)

plt.colorbar(plt.cm.ScalarMappable(cmap="coolwarm", norm=plt.Normalize(vmin=-25, vmax=25)), cax=ax1)
ax1.yaxis.set_ticks_position('left')

# plt.tight_layout()
# plt.show()

Which produces this image:

enter image description here

like image 181
Anwarvic Avatar answered Jan 19 '26 19:01

Anwarvic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!