【问题标题】:matplotlib seaborn long rownames affect other subplots' axesmatplotlib seaborn 长行名影响其他子图的轴
【发布时间】:2017-08-12 09:47:30
【问题描述】:

我想绘制一张表格,我真的很喜欢 seaborn。所以我写了一个简单的函数,它返回一个 seaborn 热图并用一些灰色填充单元格。 我的问题是,当我在子图中使用该表时,沿垂直轴的其他图会缩小到我在其上绘制 seaborn 热图的轴的宽度。

import seaborn as sns
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

def plotTable(tableDf, ax=None):
    s = len(tableDf), len(tableDf.columns)
    dataZeros = np.zeros(s)
    dataTableFake = pd.DataFrame(dataZeros, index=tableDf.index, columns=tableDf.columns)
    dataTable = tableDf.values.astype(str)

    col = ["#dbdada"]
    my_cmap = ListedColormap(col)
    ax = sns.heatmap(dataTableFake, cmap=my_cmap, annot_kws={"size": 8}, cbar=False, linewidths=0.5,
                     square=False, ax=ax, annot = dataTable, fmt = '')
    ax.xaxis.tick_top()
    ax.set_yticklabels(ax.get_yticklabels(), rotation=0)


table = pd.DataFrame(dict(value01=1.01,
                          value02=2.02,
                          value03=3.03),
                          index=["This is a pretty long index and I dont't want it to shrink the other subplots"])

gs = gridspec.GridSpec(2, 1)

ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[1, 0])

plotTable(tableDf=table, ax=ax1)
plt.tight_layout()

创建以下图:

我不希望第二个轴(即 ax2)受到 ax1 中行名长度的影响。我希望这能说明我的意思:

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    您可以在 2 行和 3 列上定义一个网格规范,并将“表格”放置在第一行最右边的子图中。然后另一个图可以跨越第二行中的所有 3 个子图位置。

    gs = gridspec.GridSpec(2, 3)
    ax1 = plt.subplot(gs[0, 2])
    ax2 = plt.subplot(gs[1, :])
    

    最后,不要打电话给tight_layout,因为这会搞砸一切。如果需要调整间距,使用plt.subplots_adjust(...)手动设置

    【讨论】:

    • 谢谢欧内斯。我知道了。没有机会在这里使用tight_layout?
    • 正如我所说,tight_layout 会尝试解释布局,但它不会按照您想要的方式进行。但是你为什么还需要它呢?
    • 它会自动处理重叠的轴标题,这对我需要的绘图很方便。
    • 如前所述,使用例如plt.subplots_adjust(hspace=0.3) 而不是 tight_layout。选择不重叠的数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2019-09-10
    • 2016-02-29
    • 1970-01-01
    • 2020-08-26
    • 2019-12-07
    相关资源
    最近更新 更多