我在带有明显名称的分类热图上标注了颜色栏。绘制时,这些名称并不完全可见。 plt.tight_layout()
破坏了元素的排列,有时不显示热图刻度线或不按比例缩放颜色条和热图。我如何在不引入其他问题的情况下自动增大身材?
这里是一个示例:
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
import matplotlib
n_labs = 4
labels = np.floor(np.random.rand(10, 10) * n_labs)
names = np.array(['a'*20] * n_labs)
bounds = np.linspace(-0.5, n_labs - 0.5, n_labs + 1)
norm = matplotlib.colors.BoundaryNorm(bounds, n_labs)
fmt = matplotlib.ticker.FuncFormatter(
lambda z, pos: names[norm(z)]
)
plt.figure()
plt.suptitle('Title')
sns.heatmap(
labels, cmap=plt.get_cmap('copper', n_labs), square=True, linewidths=1, vmax=n_labs,
cbar_kws=dict(
ticks=np.arange(n_labs), format=fmt,
boundaries=bounds, drawedges=True
),
)
plt.tight_layout()
plt.show()
不带tight_layout
的结果:
答案 0 :(得分:0)
在我看来,seaborn正在对边界框进行一些奇怪的计算;无论如何,我以前在plt.tight_layout()
的“聪明猜测”中也遇到了很多问题,现在我通常使用gridspec
对图形布局进行更细粒度的控制(控制多个图形的好处更多)子图):
from matplotlib import gridspec
####
omitting your data code here for simplicity...
####
fig=plt.figure(figsize=(3,3),dpi=96,) ##### figure size in inch
gs = gridspec.GridSpec(1, 1, ##### a 1x1 subplot grid
left=0.1,right=0.7, #####<—— play with these values,
bottom=0.0,top=1.0, ##### they give the margins as percentage of the figure
wspace=0.0,hspace=0.0, #####<—- this controls additional padding around the subplot
)
ax = fig.add_subplot(gs[0]) ##### add the gridspec subplot gs[0]
ax.set_title('Title')
sns.heatmap(
labels, cmap=plt.get_cmap('copper', n_labs), square=True, linewidths=1, vmax=n_labs,
cbar_kws=dict(
ticks=np.arange(n_labs), format=fmt,
boundaries=bounds, drawedges=True,
shrink=0.6
),
ax=ax #####<—— it is important to let seaborn know which subplot to use
)
——————————
为了使事情或多或少地自动,请尝试像这样绘制:
fig,axes=plt.subplots(1,2, gridspec_kw = {'width_ratios':[20, 1]},figsize=(3,3))
cbar_ax=axes[1]
ax=axes[0]
ax.set_title('Title')
sns.heatmap(
labels, cmap=plt.get_cmap('copper', n_labs), square=True, linewidths=1, vmax=n_labs,
cbar_kws=dict(
ticks=np.arange(n_labs), format=fmt,
boundaries=bounds, drawedges=True,
shrink=0.1,
),
cbar_ax=cbar_ax, #####< it is important to let seaborn know which subplot to use
ax=ax #####< it is important to let seaborn know which subplot to use
)
plt.tight_layout()
plt.show()
这里您要创建两个子图(ax
和cbar_ax
),其中width_ratio
为20:1
,然后告诉sns.heatmap
实际使用这些轴。 plt.tight_layout()
似乎工作得更好,并且尽可能自动运行,但是仍然会遇到问题(例如,通过设置figsize=(2,2)
会抛出ValueError: left cannot be >= right