缩放图形以显示长注释

2024-06-17 11:55:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我用冗长的名字在一个分类热图上标注了一个颜色条。打印时,这些名称不完全可见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和有tight_layout的结果:

Without

With


Tags: importnormlabelsnamesmatplotlib颜色asnp
1条回答
网友
1楼 · 发布于 2024-06-17 11:55:11

在我看来,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()    

在这里,您将创建两个子图(axcbar_ax),其中width_ratio20:1,然后告诉sns.heatmap实际使用这些轴plt.tight_layout()似乎工作得更好,并且尽可能自动,但仍然会遇到问题(例如,通过设置figsize=(2,2)它将抛出ValueError: left cannot be >= right

相关问题 更多 >