Reputation: 6132
Today I'm working on a heatmap inside a function. It's nothing too fancy: the heatmap shows a value for every district in my city and inside the function one of the arguments is district_name
.
I want my function to print this same heatmap, but that it highlights the selected district (preferably through bolded text).
My code is something like this:
def print_heatmap(district_name, df2):
df2=df2[df2.t==7]
pivot=pd.pivot_table(df2,values='return',index= 'district',columns= 't',aggfunc ='mean')
sns.heatmap(pivot, annot=True, cmap=sns.cm.rocket_r,fmt='.2%',annot_kws={"size": 10})
So I need to access ax's values, so I can bold, say "Macul" if I enter print_heatmap('Macul',df2)
. Is there any way I can do this?
What I tried was to use mathtext
but for some reason I can't use bolding in this case:
pivot.index=pivot.index.str.replace(district_name,r"$\bf{{{}}}$".format(district_name)
But that brings:
ValueError:
f{macul}$
^
Expected end of text (at char 0), (line:1, col:1)
Thanks
Upvotes: 3
Views: 4054
Reputation: 1007
I think it is hard to do this explicitly in seaborn, you can instead though iterate through the texts in the axes (annot) and the ticklabels and set their properties to "highlight" a row.
Here is an example of this approach.
import matplotlib as mpl
import seaborn as sns
import numpy as np
fig = plt.figure(figsize = (5,5))
uniform_data = np.random.rand(10, 1)
cmap = mpl.cm.Blues_r
ax = sns.heatmap(uniform_data, annot=True, cmap=cmap)
# iterate through both the labels and the texts in the heatmap (ax.texts)
for lab, annot in zip(ax.get_yticklabels(), ax.texts):
text = lab.get_text()
if text == '2': # lets highlight row 2
# set the properties of the ticklabel
lab.set_weight('bold')
lab.set_size(20)
lab.set_color('purple')
# set the properties of the heatmap annot
annot.set_weight('bold')
annot.set_color('purple')
annot.set_size(20)
Upvotes: 5