今天我正在函数内制作热图。这没什么太奇特的:热图显示了我所在城市每个地区的值,并且在函数内部,参数之一是 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})
所以我需要访问 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)
关于python - 突出显示 Seaborn 热图中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405962/