gpt4 book ai didi

python - Seaborn 热图 : underline text in a cell

转载 作者:行者123 更新时间:2023-11-30 21:54:55 24 4
gpt4 key购买 nike

我正在用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"或"斜”。

有解决办法吗?

最佳答案

是的,您可以在文本中使用 tex 命令来解决您的问题。基本思想是使用seaborn.heatmap 的annot 键将字符串数组指定为文本标签。这些包含您的数据值+一些 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()

进一步解释注释数组:

# For all matrix_elements in your 2D data array (2D requires the .ravel() and .reshape() 
# stuff at the end) construct in sum a 2D data array consisting of strings
# \textbf{\emph{\underline{<matrix_element>}}}. Each string will be represented by tex as
# a bold, italic and underlined representation of the matrix_element
np.array([r'\textbf{\emph{\underline{' + str(data) + '}}}'
for data in data_matrix.ravel()]).reshape(np.shape(data_matrix))

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

enter image description here

关于python - Seaborn 热图 : underline text in a cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com