matplotlib seaborn 长行名影响其他子图的轴
matplotlib seaborn long rownames affect other subplots' axes
我想画一个table,我很喜欢seaborn。所以我写了一个简单的函数,returns 一个 seaborn 热图并用一些灰色填充单元格。
我的问题是,当我在子图中使用 table 时,沿垂直轴的其他图正在缩小到我在其上绘制 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 列上定义一个 gridspec,并将 "table" 放在第一行最右边的子图中。然后另一个图可以跨越第二行中的所有 3 个子图位置。
gs = gridspec.GridSpec(2, 3)
ax1 = plt.subplot(gs[0, 2])
ax2 = plt.subplot(gs[1, :])
最后,不要调用 tight_layout
,因为这会把一切搞砸。如果您需要调整间距,请使用 plt.subplots_adjust(...)
手动设置它们
我想画一个table,我很喜欢seaborn。所以我写了一个简单的函数,returns 一个 seaborn 热图并用一些灰色填充单元格。 我的问题是,当我在子图中使用 table 时,沿垂直轴的其他图正在缩小到我在其上绘制 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 列上定义一个 gridspec,并将 "table" 放在第一行最右边的子图中。然后另一个图可以跨越第二行中的所有 3 个子图位置。
gs = gridspec.GridSpec(2, 3)
ax1 = plt.subplot(gs[0, 2])
ax2 = plt.subplot(gs[1, :])
最后,不要调用 tight_layout
,因为这会把一切搞砸。如果您需要调整间距,请使用 plt.subplots_adjust(...)