如何调整Matplotlib图例中同一条目下两个标记的间距?
调整Matplotlib图例同一条目内两个标记的间距
你使用HandlerTuple在Matplotlib图例的单个条目中放置两个标记,目前可以通过handletextpad调整标记与文本的间距,但不知道如何调整两个标记之间的间距。
解决方案
核心是利用HandlerTuple类的**pad参数**,它专门用于控制同一图例条目内多个handle(标记/线条)之间的水平间距,单位为字体大小的倍数。
修改代码中handler_map部分的HandlerTuple初始化,添加pad参数即可:
import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerTuple fig, ax1 = plt.subplots(1, 1) # First plot: two legend keys for a single entry p1, = ax1.plot([1, 2], [5, 6], '-', marker='o', markersize=2, mfc="gray", mec="gray") p2, = ax1.plot([1], [5], "-k", marker='s', markersize=10) p3, = ax1.plot([3, 4], [2, 3], 'o', mfc="white", mec="k") p4, = ax1.plot([3], [2], '-k', mfc="white", mec="k") # Assign two of the handles to the same legend entry by putting them in a tuple handles = [(p1, p2), (p3, p4)] l = ax1.legend( handles, ['data', 'models'], # 调整pad参数控制两个标记的间距,值越大间距越宽 handler_map={tuple: HandlerTuple(ndivide=None, pad=2.0)}, handletextpad=1, columnspacing=2.0, ncol=1, ) plt.show()
补充说明
pad的默认值为0.5,可根据需求调整为更大(如2.0)或更小(如0.2)的数值;- 如果需要更个性化的布局控制,还可以自定义
HandlerTuple的子类,重写create_artists方法精确控制每个标记的位置,但对于大多数场景,pad参数已足够满足需求。
内容的提问来源于stack exchange,提问作者Natasha
相关产品推荐
相关产品推荐

