突出显示seaborn热图中的一行

Jua*_*n C 2 python graph matplotlib seaborn

今天我正在研究一个函数内的热图。没什么太花哨的:热图显示了我城市中每个区的值,并且在函数内部,其中一个参数是district_name

热图

我希望我的函数打印相同的热图,但它会突出显示所选区域(最好通过粗体文本)。

我的代码是这样的:

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})
Run Code Online (Sandbox Code Playgroud)

所以我需要访问 ax 的值,所以我可以加粗,如果我输入print_heatmap('Macul',df2). 有什么办法可以做到这一点吗?

我尝试的是使用mathtext但由于某种原因我不能在这种情况下使用粗体:

pivot.index=pivot.index.str.replace(district_name,r"$\bf{{{}}}$".format(district_name)
Run Code Online (Sandbox Code Playgroud)

但这带来了:

ValueError: 
f{macul}$
^
Expected end of text (at char 0), (line:1, col:1)
Run Code Online (Sandbox Code Playgroud)

谢谢

dja*_*sky 5

我认为在 seaborn 中很难明确地做到这一点,您可以改为遍历轴(注释)和刻度标签中的文本并将它们的属性设置为“突出显示”一行。

下面是这种方法的一个例子。

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明