Cactus Philosopher
Cactus Philosopher

Reputation: 864

Matplotlib - specific column of legend label

import matplotlib.pyplot as plt
import numpy as np

N = 10

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='1')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='2')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='3')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='4')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='5')

plt.legend(ncol=2, loc='upper left')

plt.show()

enter image description here

I'd like to move label '3' to the second column of the legend.

So column one should have:
1
2

And column two should have:
3
4
5

How can I do this?

Upvotes: 0

Views: 1357

Answers (1)

Elliot Su
Elliot Su

Reputation: 176

You can put on a blank label before scatter the label 3 points with label color identical to your background color:

import matplotlib.pyplot as plt
import numpy as np

N = 10

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='1')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='2')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='', c='#ffffff')
plt.scatter(x, y, label='3')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='4')

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, label='5')
plt.legend(labels=['1','2', '', '3','4','5'], ncol=2, loc='upper left')
plt.show()

enter image description here

Notice that if the labels parameters not specified in plt.legend then the output will be the same as yours since it skip drawing the blank label.

Upvotes: 2

Related Questions