我想绘制一个表格,我真的很喜欢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 中行名长度的影响。我希望这能清楚地表达我的意思:
最佳答案
您可以定义 2 行 3 列的网格规范,并将“表格”放置在第一行最右侧的子图中。然后,另一个图可以跨越第二行中的所有 3 个子图位置。
gs = gridspec.GridSpec(2, 3)
ax1 = plt.subplot(gs[0, 2])
ax2 = plt.subplot(gs[1, :])
最后,不要打电话tight_layout
因为这把一切都搞乱了。如果需要调整间距,请使用plt.subplots_adjust(...)
手动设置它们。
关于python - matplotlib seaborn 长行名影响其他子图的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915067/