Skip to main content
 首页 » 编程设计

python之图例框中的文本和图标对齐(matplotlib)

2024年10月24日11落叶无声

我想减小图例中的文本大小,以便 tikz 数字可以保持相对较大。问题是当我减小图例中字体的大小时,图例中的图标和文本之间的对齐方式会受损。我怎样才能再次配对它们? 以下是测试:

import numpy as np 
from  matplotlib import pyplot as plt 
plt.rc('text', usetex = True) 
font = {'family' : 'normal', 
        'weight' : 'normal', 
        'size'   : 25} 
plt.rc('font', **font) 
fig, ax = plt.subplots(1, 1) 
a = np.arange(10) 
b = np.random.randn(10) 
ax.errorbar(a, b, yerr=0.5, fmt='o', color='g', ecolor='g', capthick=1, linestyle = '-', linewidth=2, elinewidth=1, label = "Test") 
legend = plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=6, mode="expand", borderaxespad=0.2) 
plt.setp(legend.get_texts(), fontsize='15') #legend 'list' fontsize 
fig.set_size_inches(14.5, 10.5) 
plt.savefig('/Users/Cupitor/Test.png') 

正如您在下图中所看到的,图例中的文本相对于其左侧的绿色图形不再居中:

请您参考如下方法:

我在 Python 2.7 和 3.3、Ubuntu 15.04、matplotlib 1.4.2 和使用 Agg 后端时遇到同样的问题。貌似直接设置图例文字艺术家的fontsize后,无论是通过plt.setp还是使用set_size方法,文字都没有无论用于文本垂直对齐的选项('center'、'top'、'bottom'、'baseline')如何,都与其相应的句柄正确地垂直居中对齐。

我发现解决此问题的唯一方法是手动将文本边界框的高度与 handle 边界框的高度对齐。根据您在 OP 中提供的代码,下面是一个示例,说明如何完成此操作:

import matplotlib as mpl 
mpl.use('TkAgg') 
import numpy as np 
from  matplotlib import pyplot as plt 
 
plt.close('all') 
 
plt.rc('text', usetex = True) 
font = {'family' : 'normal', 
        'weight' : 'normal', 
        'size'   : 25} 
plt.rc('font', **font) 
 
fig = plt.figure() 
fig.set_size_inches(14.5, 10.5) 
ax = fig.add_axes([0.1, 0.1, 0.85, 0.75]) 
 
#---- plot some data ---- 
 
ax.plot(np.arange(10), np.random.randn(10), 'rd', ms=15, 
        label='The quick brown fox...') 
 
ax.errorbar(np.arange(10), np.random.randn(10), yerr=0.5, fmt='o', 
            color='g', ecolor='g', capthick=1,ls = '-', lw=2, elinewidth=1,  
            label = "... jumps over the lazy dog.") 
 
#---- plot legend ---- 
 
legend = plt.legend(bbox_to_anchor=(0., 1.02, 1., 0.), handletextpad=0.3, 
                    loc='lower left', ncol=6, mode="expand", borderaxespad=0, 
                    numpoints=1, handlelength=0.5) 
 
#---- adjust fontsize and va ---- 
 
plt.setp(legend.get_texts(), fontsize='15', va='bottom') 
 
#---- set legend's label vert. pos. manually ---- 
 
h = legend.legendHandles 
t = legend.texts 
renderer = fig.canvas.get_renderer() 
 
for i in range(len(h)): 
    hbbox = h[i].get_window_extent(renderer) # bounding box of handle 
    tbbox = t[i].get_window_extent(renderer) # bounding box of text 
 
    x = tbbox.x0 # keep default horizontal position     
    y = (hbbox.height - tbbox.height) / 2. + hbbox.y0 # vertically center the 
    # bbox of the text to the bbox of the handle. 
 
    t[i].set_position((x, y)) # set new position of the text 
 
plt.show(block=False) 
plt.savefig('legend_text_va.png') 

结果是:

在 plt.setp 中设置 va='bottom' 似乎会产生更好的结果。我相信当垂直对齐设置为底部时,文本的 bbox 会更准确,但我还没有进一步调查来证实这一点。