在seaborn热图中突出显示一行

2024-06-01 18:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

今天我在做一个函数内部的热图。这没什么好奇怪的:热图显示了我城市中每个地区的值,函数内部的参数之一是district_name。在

heatmap

我希望我的功能打印相同的热图,但它突出显示选定的地区(最好是通过粗体文本)。在

我的代码是这样的:

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

所以我需要访问ax的值,所以如果我输入print_heatmap('Macul',df2),我可以粗体说“Macul”。我有办法吗?在

我试图使用mathtext,但由于某些原因,在这种情况下我不能使用粗体:

^{pr2}$

但这带来了:

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

谢谢


Tags: 函数name文本功能参数地区pivot热图
1条回答
网友
1楼 · 发布于 2024-06-01 18:19:41

我认为在seaborn中很难明确地做到这一点,您可以通过迭代轴(annot)和ticklabels中的文本并将它们的属性设置为“高亮显示”一行。在

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

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)

enter image description here

相关问题 更多 >