如何创建水平对齐的2个点(打开和填充)的matplotlib图例条目?

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

我想创建一个图例条目,其中显示两个标记,其中一个打开,另一个填充。我已经尝试使用plt.scatterplt.plot来做到这一点,但是我遇到了麻烦之一:

  • 使用plt.scatter:使用scatterpoints > 2时,图例中各点之间似乎略有垂直偏移。是否可以将它们放在同一水平线上?

  • plt.plot:是否可以单独修改图例标记以将其中一个打开并填充一个?

# plot random data to host the legend:

# scatter option
plt.scatter(-1, -1,
            facecolor='k', edgecolor='k', 
            label='scatter')
# plot option
plt.plot(-1, -1, lw=0, 
         marker='o', markerfacecolor='k', markeredgecolor='k', label='plot')

# add legend
leg = plt.legend(scatterpoints=2, numpoints=2)

# modify scatter points -- have an unwanted vertical offset?
leg.legendHandles[1].set_facecolors(['None', 'k'])
leg.legendHandles[1].set_edgecolors(['k', 'k'])

# modify plot points -- cannot change individual markers?
leg.legendHandles[0].set_markeredgecolor(['None', 'k'])
leg.legendHandles[0].set_markeredgecolor(['k', 'k'])

Attempt to create legend with open and filled points

python matplotlib
2个回答
1
投票

this question的答案可以修改为您想要做的:

class HandlerTupleHorizontal(HandlerTuple):
def __init__(self, **kwargs):
    HandlerTuple.__init__(self, **kwargs)

def create_artists(self, legend, orig_handle,
                   xdescent, ydescent, width, height, fontsize, trans):
    # How many lines are there.
    numlines = len(orig_handle)
    handler_map = legend.get_legend_handler_map()

    # divide the horizontal space where the lines will go
    # into equal parts based on the number of lines
    width_x = (width / numlines)

    leglines = []
    for i, handle in enumerate(orig_handle):
        handler = legend.get_legend_handler(handler_map, handle)

        legline = handler.create_artists(legend, handle,
                                         xdescent,
                                         height,
                                         (2 * i + 1) * width_x,
                                         2 * height,
                                         fontsize, trans)

        leglines.extend(legline)

    return leglines

然后您只需执行以下操作:

l1, = plt.plot(-1, -1, lw=0, marker="o",
               markerfacecolor='k', markeredgecolor='k')
l2, = plt.plot(-0.5, -1, lw=0, marker="o",
               markerfacecolor=None, markeredgecolor='k')

plt.legend([tuple([l1, l2])], ["test"],
           handler_map={tuple: HandlerTupleHorizontal()},
           loc=1, frameon=True, framealpha=0.8)

Legend with open and filled points


0
投票

可以通过设置scatteryoffsetsplt.legend参数水平地将散射点对齐:

leg = plt.legend(scatterpoints=2, scatteryoffsets=[0.5])

Documentation

scatteryoffsets:可迭代的浮点数

为散点图图例条目创建的标记的垂直偏移量(相对于字体大小)。 0.0在图例文本的底部,而1.0在顶部。要以相同的高度绘制所有标记,请设置为[0.5]。默认值为[0.375, 0.5, 0.3125]

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