如何将matplotlib图例中的行与2列对齐

Sam*_*ise 5 python matplotlib

我有一个问题,一些mathtext格式化使一些标签比其他标签占用更多的垂直空间,这导致它们在图例中放置在两列时不排队.这一点尤其重要,因为行也用于指示相关数据.

这是一个例子:

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext
mpl.rc("font", family="Times New Roman",weight='normal')
plt.rcParams.update({'mathtext.default':  'regular' })
plt.plot(1,1, label='A')
plt.plot(2,2, label='B')
plt.plot(3,3, label='C')
plt.plot(4,4,label='$A_{x}^{y}$')
plt.plot(5,5,label='$B_{x}^{y}$')
plt.plot(6,6,label='$C_{x}^{y}$')
plt.legend(fontsize='xx-large', ncol=2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

这会生成如下图: 在此输入图像描述

有一段时间,我能够通过添加一些空的下标和上标来"伪造"一些,但是这只有在情节导出为pdf时才有效.导出到png时似乎不起作用.如何展开第一列标签,使它们与第二列对齐?

Imp*_*est 13

您可以将handleheight关键字参数设置为一个足够大的数字,使得句柄的高度大于字体占用的空间.这使文本显示为对齐.这样做可能需要将其设置labelspacing为较小的数字,以免使图例显得过大.

plt.legend(fontsize='xx-large', ncol=2,handleheight=2.4, labelspacing=0.05)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

从图中可以看出,这种方法的缺点是线条与文本的基线相比向上移动.如果这是可接受的,它可能会依赖于用例.

如果不是,那就需要深入挖掘一下.以下子类HandlerLine2D(为行的处理程序)以便为行设置略微不同的位置.根据总的传说大小,字体大小等一个需要去适应的数量xxSymHandler类.

from matplotlib.legend_handler import HandlerLine2D
import matplotlib.lines

class SymHandler(HandlerLine2D):
    def create_artists(self, legend, orig_handle,xdescent, ydescent, width, height, fontsize, trans):
        xx= 0.6*height
        return super(SymHandler, self).create_artists(legend, orig_handle,xdescent, xx, width, height, fontsize, trans)

leg = plt.legend(handler_map={matplotlib.lines.Line2D: SymHandler()}, 
            fontsize='xx-large', ncol=2,handleheight=2.4, labelspacing=0.05) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述