matplotlib 图例中的选择性垂直空格

Selective vertical whitespace in matplotlib legend

我正在尝试在使用 matplotlib.pyplot 生成的图例中创建一些额外的垂直空白。但是,希望这个额外的空白仅位于图例中的两个条目之间,而其余条目保持不变。我有一个 MWE 及其生成的图像,经过编辑以显示我想要额外空白的位置。

import matplotlib.pyplot as plt

plt.plot([0,1],[.2,.2],label = "A")
plt.plot([0,1],[.4,.4],label = "B")
plt.plot([0,1],[.6,.6],label = "C")
plt.plot([0,1],[.8,.8],label = "D")

plt.legend(loc='upper right',labelspacing=.3)
plt.ylim(0,1)

plt.show()

您可能需要为此使用代理艺术家。这是一个例子:

a, = plt.plot([0,1],[.2,.2],label = "A")
b, = plt.plot([0,1],[.4,.4],label = "B")
c, = plt.plot([0,1],[.6,.6],label = "C")
d, = plt.plot([0,1],[.8,.8],label = "D")

plt.legend([a,b,c,matplotlib.lines.Line2D([],[],linestyle=''),d],['A','B','C','','D'], loc='upper right',labelspacing=.3)
plt.ylim(0,1)

您可以在标签中使用 \n

请注意,标签以标记为中心,因此使用 2 \n

plt.plot([0,1],[.6,.6],label = "\nC\n")