How to modify the text arrangement in legend

Viewed 49

I want to customize the number of rows in each column of the matplotlib legend text.

The code is:

import matplotlib.pyplot as plt
import numpy as np

for i in range(10):
    plt.plot(np.linspace(0, 5, 5), np.random.randint(0, 10, 5), label=str(i))

plt.legend(ncol = 3, loc = 1)
plt.show()

What I get: the numbers of rows in each column are 4, 3, 3 enter image description here

What I want: the numbers of rows in each column are 4, 4, 2

enter image description here

I've tried adding plt.plot([], [], label='') before plt.show(), but it doesn't help

1 Answers

I solved this problem by adding an invisible line as 11th element like this:

import matplotlib.pyplot as plt
import numpy as np

lines = []
for i in range(10):
    l, = plt.plot(np.linspace(0, 5, 5), np.random.randint(0, 10, 5), label=str(i))
    lines.append(l)

l, = plt.plot(0, alpha=0, label=' ')   
# alpha=0 will make the line and element in the legend invisible
lines.append(l)

plt.legend(handles=[l for l in lines], ncol = 3, loc = 1)
plt.show()

This will yield the following result: enter image description here

Related