python - 重叠的 yticklabels : Is it possible to control cell size of heatmap in seaborn?

标签 python matplotlib heatmap axis-labels seaborn

我有一个包含大约 200 个观测值的数据集,我想将其绘制为热图。每个观察都有一个与之关联的字符串,我想显示它。我的问题是我无法阅读这些标签,因为它们相互重叠。因此,我的问题是,是否可以以某种方式将热图的单元格大小设置为 yticklabel 的字体大小,或者是否有任何其他解决方法。

在下面的示例中,我使用随机数据进行说明:

import seaborn as sns
import numpy as np
data = np.random.rand(200, 10)
ax = sns.heatmap(data)
for item in ax.get_yticklabels():
    item.set_rotation(0)

这给了我:

enter image description here

有没有办法让这些 yticklabels 可读?在理想情况下,我会有一个选项允许我将单元格的高度设置为 yticklabels 的字体大小。这可能吗?

编辑:

如评论中所述,一种可能性是增加图形的大小。我试过如下:

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

data = np.random.rand(200, 10)

fig, ax = plt.subplots()
fig.set_size_inches(38.5, 10.5)

ax2 = sns.heatmap(data, ax=ax)
for item in ax2.get_yticklabels():
    item.set_rotation(0)

这给了我相同的输出。我是否正确使用它?

最佳答案

为标签腾出更多空间的唯一方法是增加矩阵的高度。唯一的其他选择是减小字体大小,但我想这不是您想要的。 因此,您可以根据矩阵中的行数和标签的字体大小来计算理想的图形高度。当您保存生成的图时,您会得到预期的结果。您在调用 plt.show() 时看到的 GUI 窗口的高度似乎限于屏幕高度:

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

# create some random data
data = np.random.rand(150, 10)

# get the tick label font size
fontsize_pt = plt.rcParams['ytick.labelsize']
dpi = 72.27

# comput the matrix height in points and inches
matrix_height_pt = fontsize_pt * data.shape[0]
matrix_height_in = matrix_height_pt / dpi

# compute the required figure height 
top_margin = 0.04  # in percentage of the figure height
bottom_margin = 0.04 # in percentage of the figure height
figure_height = matrix_height_in / (1 - top_margin - bottom_margin)


# build the figure instance with the desired height
fig, ax = plt.subplots(
        figsize=(6,figure_height), 
        gridspec_kw=dict(top=1-top_margin, bottom=bottom_margin))

# let seaborn do it's thing
ax = sns.heatmap(data, ax=ax)

# save the figure
plt.savefig('/tmp/test.png')

结果:

enter image description here

关于python - 重叠的 yticklabels : Is it possible to control cell size of heatmap in seaborn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127920/

相关文章:

python - 多个处理器记录到同一个旋转文件

python - Matplotlib 条形图 - 一些条形不可见并且宽度似乎不同

python - 从 pandas DataFrame 制作热图

javascript - 带有新数据集的动画热图

python - socket.gaierror : [Errno 11001] getaddrinfo failed

python - 无法通过 WSL 使用 conda 显示 matplotlib 的输出

python - 使用 Tastypie 公开模型方法

Python实时变化的热图绘制

python - 如何从 Pandas 绘图函数返回 matplotlib.figure.Figure 对象

r - X 轴标签位于绘图区域顶部