【问题标题】:Draw a line on a legend in pyplot [duplicate]在pyplot中的图例上画一条线[重复]
【发布时间】:2020-01-07 02:29:14
【问题描述】:

我正在尝试在绘图中的图例上画一条线以分隔顶部和底部行。目前图例如下图所示

Image of legend without a line to separate rows

plt.legend 中是否有任何属性可以绘制水平线,或者是否有任何其他方法可以在图例中绘制一条线,如下图所示:

Image of legend with a line to separate rows

非常感谢!

【问题讨论】:

标签: python matplotlib


【解决方案1】:

实际上,一种正统的方法是将图例完全分开。 您可以参考this link,或参考同一链接中的sn-p:

line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)

# Create a legend for the first line.
first_legend = plt.legend(handles=[line1], loc='upper right')

# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)

# Create another legend for the second line.
plt.legend(handles=[line2], loc='lower right')

plt.show()

您会发现轴上只存在一个传奇。这样做是为了可以重复调用 legend() 以将图例更新为轴上的最新句柄,因此要保留旧的图例实例,我们必须手动将它们添加到轴:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2021-05-17
    相关资源
    最近更新 更多