python 如何在Seaborn Heatmap单元格中显示多个注解

vltsax25  于 2023-04-28  发布在  Python
关注(0)|答案(3)|浏览(148)

我希望seaborn热图在热图的每个单元格中显示多个值。这里有一个我想看到的手动示例,只是为了清楚:

data = np.array([[0.000000,0.000000],[-0.231049,0.000000],[-0.231049,0.000000]])
labels =  np.array([['A\nExtra Stuff','B'],['C','D'],['E','F']])
fig, ax = plt.subplots()
ax = sns.heatmap(data, annot = labels, fmt = '')

这里作为一个例子来获得海运。加热以显示单元格中的flightsRoundUp值。

import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

def RoundUp(x):
    return int(np.ceil(x/10)*10)

# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
flightsRoundUp =  flights.applymap(RoundUp)

# Draw a heatmap with the numeric values in each cell
f, ax = plt.subplots(figsize=(9, 6))
sns.heatmap(flights, annot=flightsRoundUp, fmt="", linewidths=.5, ax=ax)

在所有单元格中同时显示flightsRoundUpflights的最佳方法是什么?类似于上面的第一个手动示例,但以类似矢量化的方式对所有单元格进行。..

vxf3dgd4

vxf3dgd41#

Rotail的答案对我不起作用,我在应用lambda函数时出错。
然而,我发现了一个解决方案,利用了seaborn将连续的数字绘制在彼此之上的事实。您所要做的就是使用一个对heatmap的调用来建立图形,然后对每个注解进行后续调用。使用annot_kws参数确保文本不会相互覆盖。

X = pd.DataFrame({'a':[1, 2, 3], 'b':[4, 5, 6]})
Y = pd.DataFrame({'A':['A', 'B', 'C'], 'B':['E', 'F', 'G']})
Z = pd.DataFrame({'A':['(Extra Stuff)', '(Extra Stuff)', '(Extra Stuff)'], 'B':['(Extra Stuff)', '(Extra Stuff)', '(Extra Stuff)']})

sns.heatmap(X, annot=False)
sns.heatmap(X, annot=Y, annot_kws={'va':'bottom'}, fmt="", cbar=False)
sns.heatmap(X, annot=Z, annot_kws={'va':'top'}, fmt="", cbar=False)

x7yiwoj4

x7yiwoj42#

以下也适用于我:

X = pd.DataFrame({'a':[1, 2, np.nan], 'b':[10, 20, 30]})
Y = pd.DataFrame({'A':[11, 222, np.nan], 'B':[110, np.nan, 330]})

# convert to string
X_value_ann = (X).astype('|S5').reset_index()
Y_value_ann = (Y).astype('|S5').reset_index()

# define () and new line to glue on later
br = np.char.array(pd.DataFrame('\n(', index=X_value_ann.index, columns=X_value_ann.columns))
cl = np.char.array(pd.DataFrame(')', index=X_value_ann.index, columns=X_value_ann.columns))

# convert to chararray
X_value_ann = np.char.array(X_value_ann)
Y_value_ann = np.char.array(Y_value_ann)

# glue and reshape
my_annotation = pd.DataFrame(X_value_ann+br+Y_value_ann+cl)
my_annotation = my_annotation.applymap(lambda x: x.decode('utf-8')) 
my_annotation = my_annotation.drop(columns=[0])
my_annotation
4ktjp1zp

4ktjp1zp3#

你应该能够设置fmt=""和格式化你的标签与适当的"\n"有多行注解。

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

np.random.seed(0)
sns.set_theme()
uniform_data = np.random.rand(4, 4)
fig,ax = plt.subplots(figsize=(50,20))

uniform_data_labels = \[\]
for i in uniform_data:
    tmp_arr=\[\]
    for j in i:
        tmp_arr.append('Example\nExample')
    uniform_data_labels.append(tmp_arr)
    
sns.heatmap(uniform_data, vmin=0, vmax=1, annot=uniform_data_labels ,ax=ax,fmt="",annot_kws={"fontsize":30})
plt.show()

1

相关问题