Skip to content

Instantly share code, notes, and snippets.

@alex2awesome
Created December 22, 2020 00:32
Show Gist options
  • Save alex2awesome/4bf9e852a01382eef30d197f2fa5aa9e to your computer and use it in GitHub Desktop.
Save alex2awesome/4bf9e852a01382eef30d197f2fa5aa9e to your computer and use it in GitHub Desktop.
Custom Formatting for Seaborn Annotations
## Because Seaborn doesn't allow custom formatting for annotations, you have to do this crazy workaround to access the text:
def formatFloat(fmt, val):
ret = fmt % val
if ret.startswith("0."):
return ret[1:]
if ret.startswith("-0."):
return "-" + ret[2:]
return ret
ax = sns.heatmap(df_to_plot, vmin=-1, vmax=1, annot=True, cmap='seismic', square=True)#, fmt='.1g')# lambda x: formatFloat('%.2f', x))
texts = list(ax.texts)
for t in texts:
t.set_visible(False)
for t in texts:
text = t.get_text()
s = formatFloat('%.1f', float(text))
x = t._x
y = t._y
c = t._color
ax.text(x, y, s, color=c, ha="center", va="center")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment