从图中获取热图注释字典

时间:2019-07-29 13:35:24

标签: python seaborn

我有一个热点图:

fig =figsize(8,8)
ax = sbn.heatmap(good,annot=True, fmt='.2f', linewidths=.3, annot_kws={"size": 14},square=True,robust=True,cmap=sbn.light_palette((210, 90, 60), input="husl") )

enter image description here

海洋热图方便地设置注释的颜色。我想访问annot_kws词典,但是我不知道该怎么做。我本质上是想在另一图中重用seaborn自动生成的颜色。

更清晰的示例:

test = np.array([np.array([0.77,0.21]),np.array([0.21,0.51])])
ax = sbn.heatmap(test,annot=True, fmt='.2f',  annot_kws={"size": 14},cmap=sbn.light_palette((210, 90, 60), input="husl") )

给我this plot

我可以将默认注释的颜色更改为所有单一颜色

test = np.array([np.array([0.77,0.21]),np.array([0.21,0.51])])
ax = sbn.heatmap(test,annot=True, fmt='.2f',  annot_kws={"size": 14, "color":'black'},cmap=sbn.light_palette((210, 90, 60), input="husl") )

哪个给了我this picture

我想将信息传递给热图,也就是说,我可以将所有白色注解更改为黄色,而将黑色注解保留为黑色。而且我想,如果我可以获取有关当前注释颜色的信息,则可以根据是黑色还是具有不同颜色的白色来更新它们,但不知道如何实际获取该信息。

1 个答案:

答案 0 :(得分:1)

编辑:我第一次误读了您的问题。我认为这个经过修改的答案符合您的要求。

您可以通过subplots.get_children()访问注释(即Text对象)

代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.text import Text

# default colormap example
df = pd.DataFrame(np.random.normal(size=(5, 5)))
subplots = sns.heatmap(df.corr(), annot=True, annot_kws={"size": 14, "color": "black"})

# the first 5 * 5 Text objects in text_objs are the matrix annotations
# the few at the end are default annotations (title text I think) and are not
#   formatted according to to annot_kws; ignore these
text_objs = list(filter(lambda x: isinstance(x, Text), subplots.get_children()))
print(len(text_objs))
# first Text object
print(text_objs[0].get_size())
print(text_objs[0].get_color())
# last Text object
print(text_objs[-1].get_size())
print(text_objs[-1].get_color())

输出:

28
14.0
'black'
12.0
'black' # this is a coincidence