gpt4 book ai didi

python - 如何使用 matplotlib 使两个标记在图例中共享相同的标签?

转载 作者:太空狗 更新时间:2023-10-29 18:27:45 51 4
gpt4 key购买 nike

我想要的是这样的: enter image description here

我得到的是这样的: enter image description here

那么如何将标记合并为一个标签呢?同样对于线条,对于线条,当然,您可以通过在使用相同线型时不向第二条线分配标签来实现它,但是对于标记,您不能,因为它们具有不同的形状。

最佳答案

请注意,在最新版本的 matplotlib 中,您可以使用 class matplotlib.legend_handler.HandlerTuple 实现此目的如本 answer 所示还有这个 guide :

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
p2, = ax1.plot([3, 4], [2, 3], 'o', mfc="white", mec="k")
p1, = ax1.plot([1, 2], [5, 6], 's', mfc="gray", mec="gray")
# `plot` returns a list, but we want the handle - thus the comma on the left
p3, = ax1.plot([1, 5], [4, 4], "-k")
p4, = ax1.plot([2, 6], [3, 2], "-k")

# Assign two of the handles to the same legend entry by putting them in a tuple
# and using a generic handler map (which would be used for any additional
# tuples of handles like (p1, p3)).
l = ax1.legend([(p1, p2), p3], ['data', 'models'],
handler_map={tuple: HandlerTuple(ndivide=None)})

plt.savefig("demo.png")

Example script output

关于python - 如何使用 matplotlib 使两个标记在图例中共享相同的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31478077/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com