NeutronStar
NeutronStar

Reputation: 2157

Selective vertical whitespace in matplotlib legend

I'm trying to create some extra vertical whitespace in a legend produced using matplotlib.pyplot. However, want this extra whitespace to only be between two entries in the legend, while the remaining entries are left untouched. I have a MWE and the image it produces, edited to show where I want the extra whitespace.

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()

enter image description here

Upvotes: 4

Views: 7038

Answers (2)

mdede
mdede

Reputation: 37

You can use \n in labels.

Note, that the label is centered to the marker, so use 2 \n.

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

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40697

You probably have to use a Proxy Artist for this. Here is an example:

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)

enter image description here

Upvotes: 8

Related Questions