user1562862 user1562862 - 1 year ago 94
Python Question

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


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.

Answer Source

The legend is filling in the columns from left to right. In other words, if you trick it into believing that there is another line (without any text or line color in the legend), then you can populate the space under 'plot 3'.

import numpy as np
import matplotlib.pyplot as plt
from pylab import *

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

line1 = Line2D(range(10), range(10), marker='', color="red")
line2 = Line2D(range(10), range(10), marker='',color="green")
line3 = Line2D(range(10), range(10), marker='', color="blue")
line4 = Line2D(range(10), range(10), marker='', color="white")
plt.legend((line1,line4, line3,line2),('plot1','','plot3','plot2'),numpoints=1, loc=4,ncol=2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download