缩放图形以显示长注释

问题描述 投票:0回答:1

我已经为一个带有冗长名称的分类热图注释了一个颜色条。绘图时,这些名称不完全可见。 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的结果:

Without

With

python matplotlib seaborn
1个回答
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()    

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

© www.soinside.com 2019 - 2024. All rights reserved.