python - 突出显示 Seaborn 热图中的一行

标签 python matplotlib graph seaborn

今天我正在函数内制作热图。这没什么太奇特的:热图显示了我所在城市每个地区的值,并且在函数内部,参数之一是 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,但由于某种原因我在这种情况下无法使用粗体:

pivot.index=pivot.index.str.replace(district_name,r"$\bf{{{}}}$".format(district_name)

但这带来了:

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

谢谢

最佳答案

我认为在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)

enter image description here

关于python - 突出显示 Seaborn 热图中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405962/

相关文章:

python - pandas如何比较2个数据帧的行,无论顺序如何

python - 绘制从同一图形 Python 中的循环获得的两个数据帧

python : fit a curve to a list of integers

algorithm - 网格中的最佳运动

python - 从子模块导入 Python 包时避免 pylint 投诉

python - 为什么我的程序没有显示我告诉它的碰撞框?

python - 如何在 Python 中将包含几行的字符串转换为每个单元格包含一行的列表?

python - Pandas/matplotlib 线图不显示 x 轴文本标签

Java:使用 LWJGL 建模/渲染交互式六边形图形/图表

python-2.7 - 如何获得股票市场分析图表?