[英]highlight a row in seaborn heatmap
今天,我正在研究函數內部的熱圖。 太花哨了:熱圖顯示了我城市中每個區的值,並且在函數內部,其中一個參數是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})
因此,我需要訪問斧頭的值,所以如果我輸入print_heatmap('Macul',df2)
則可以加粗並說“ print_heatmap('Macul',df2)
。 有什么辦法可以做到嗎?
我嘗試使用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中明確地執行此操作,相反,您可以遍歷軸(annot)和ticklabel中的文本並將其屬性設置為“突出顯示”一行,而可以這樣做。
這是此方法的示例。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.