Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

python - Fill the right column of a matplotlib legend first

Hey I am trying to fit a legend onto a plot so that it doesn't obscure the graph.

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0,100,11)

plt.plot(X,-X, label='plot 1')
plt.plot(X,-2*X, label='plot 2')
plt.plot(X,-3*X, label='plot 3')

leg=plt.legend(ncol=2)
leg.get_frame().set_visible(False)

plt.show()

So in the minimum working example, above, what I want to be able to do is move the 'plot 2' label in the legend into the right column, i.e. directly under 'plot 3'.

Any help would be appreciated, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A diffrerent implementation of @cosmosis answer. It's probably more flexible.

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0,100,11)

plt.plot(X,-X, label='plot 1', color='red')
plt.plot(X,-2*X, label='plot 2', color='green')
plt.plot(X,-3*X, label='plot 3', color='blue')

(lines, labels) = plt.gca().get_legend_handles_labels()
#it's safer to use linestyle='none' and marker='none' that setting the color to white
#should be invisible whatever is the background
lines.insert(1, plt.Line2D(X,X, linestyle='none', marker='none'))
labels.insert(1,'')

plt.legend(lines,labels,numpoints=1, loc=4,ncol=1)

plt.show()

An other option is to create two legends as here and then displace them using bbox_to_anchor keyword here

(lines, labels) = plt.gca().get_legend_handles_labels()
leg1 = plt.legend(lines[:1], labels[:1], bbox_to_anchor=(0,0,0.8,1), loc=1)
leg2 = plt.legend(lines[1:], labels[1:], bbox_to_anchor=(0,0,1,1), loc=1)
gca().add_artist(leg1)

doing it I get this without the need of add any on other object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...