Seaborn热图:下划线文本

2024-04-24 23:55:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python进行一些数据分析,并使用Seaborn进行可视化。 Seaborn非常适合制作热图。在

我试图在我的热图中每列的最大值下划线。在

我能够正确地突出显示最大单元格中的文本,方法是使它们斜体粗体。尽管如此,我还是没法在上面画线。在

下面是我的代码示例:


data_matrix = < extract my data and put them into a matrix >
max_in_each_column = np.max(data_matrix, axis=0)

sns.heatmap(data_matrix,
            mask=data_matrix == max_in_each_column,
            linewidth=0.5,
            annot=True,
            xticklabels=my_x_tick_labels,
            yticklabels=my_y_tick_labels,
            cmap="coolwarm_r")

sns.heatmap(data_matrix,
            mask=data_matrix != max_in_each_column,
            annot_kws={"style": "italic", "weight": "bold"},
            linewidth=0.5,
            annot=True,
            xticklabels=my_x_tick_labels,
            yticklabels=my_y_tick_labels,
            cbar=False,
            cmap="coolwarm_r")

这是我目前的结果: My current heatmap, with maximum values for each column *italic* and **bold**

当然,我尝试过使用参数annot_kws={"style": "underlined"},但显然在Seaborn中,“style”键只支持值“normal”、“italic”或“斜交”。在

有什么解决办法吗?在


Tags: indatalabelsstylemycolumnseabornmatrix
1条回答
网友
1楼 · 发布于 2024-04-24 23:55:43

是的,你可以在文本中使用tex命令来解决你的问题。基本思想是使用seaborn.heatmapannot键来分配一个字符串数组作为文本标签。这些包含您的数据值+一些tex前缀/后缀,允许tex将其加粗/强调(斜体)/下划线或任何其他内容。在

一个例子(随机数):

# random data
data_matrix = np.round(np.random.rand(10, 10), decimals=2)
max_in_each_column = np.max(data_matrix, axis=0)

# Activating tex in all labels globally
plt.rc('text', usetex=True)
# Adjust font specs as desired (here: closest similarity to seaborn standard)
plt.rc('font', **{'size': 14.0})
plt.rc('text.latex', preamble=r'\usepackage{lmodern}')

# remains unchanged
sns.heatmap(data_matrix,
            mask=data_matrix == max_in_each_column,
            linewidth=0.5,
            annot=True,
            cmap="coolwarm_r")

# changes here
sns.heatmap(data_matrix,
            mask=data_matrix != max_in_each_column,
            linewidth=0.5,
            # Use annot key with np.array as value containing strings of data + latex 
            # prefixes/suffices making the bold/italic/underline formatting
            annot=np.array([r'\textbf{\emph{\underline{' + str(data) + '}}}'
                            for data in data_matrix.ravel()]).reshape(
                np.shape(data_matrix)),
            # fmt key must be empty, formatting error otherwise
            fmt='',
            cbar=False,
            cmap="coolwarm_r")

plt.show()

注释数组的进一步说明:

^{pr2}$

结果图基本上就是你想要的:

enter image description here

相关问题 更多 >