python - matplotlib seaborn 长行名影响其他子图的轴

标签 python pandas matplotlib seaborn

我想绘制一个表格,我真的很喜欢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()

创建以下图:

enter image description here

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

enter image description here

最佳答案

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

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

最后,不要打电话tight_layout因为这把一切都搞乱了。如果需要调整间距,请使用plt.subplots_adjust(...)手动设置它们。

enter image description here

关于python - matplotlib seaborn 长行名影响其他子图的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915067/

相关文章:

python - Pandas 中按月份和任意属性求和和绘图

python - 筛选比较,计算相似度得分,python

python - Numpy 获取每列的 dtype

python 缩进错误( tensorflow )

python - pandas 按多个值过滤列值

python - 在一系列时间索引上绘制 DataFrame

python - matplotlib 路径线宽连接到图形缩放

python - Ubuntu : error using cv2. imshow() 与 pyplot.plot()

python - scapy 没有发送数据包

python - pycharm Manage.py任务导入错误: No module named manage