Klem
Klem

Reputation: 59

matplotlib.pyplot.scatter - define sizes of entries in legend for size of marker

How to change the marker size and the respective label in the legend to meaningful values like [20,40,60,80] ? Do I need to derive handles and labels from an additional dummy dataset and how to plot it, so that it will not be visible (alpha=0.0 will not work?)?

enter image description here

import matplotlib.pyplot as plt
import numpy as np

x = [1,2,3,4,5]
y = [1,2,3,4,5]
size = np.asarray([0.84,0.53,0.24,0.47,0.18]) * 100

s1 = plt.scatter(x, y, s=size)
handles, labels = s1.legend_elements(prop="sizes")
legend2 = plt.legend(handles, labels, frameon=False, title="Sizes")

plt.show()

Upvotes: 0

Views: 279

Answers (1)

JohanC
JohanC

Reputation: 80299

The function legend_elements(...) has a parameter num= which can be a Locator. So, you can try e.g. a MultipleLocator:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
size = np.asarray([0.84, 0.53, 0.24, 0.47, 0.18]) * 100

s1 = plt.scatter(x, y, s=size)
handles, labels = s1.legend_elements(prop="sizes", num=MultipleLocator(20))
legend2 = plt.legend(handles, labels, frameon=False, title="Sizes")

plt.show()

using legend_elements with a locator

PS: In this case, you can also just put a number for num=, e.g. s1.legend_elements(prop="sizes", num=4). That also seems to put rounded values. When only a few different size values are used in the plot, the default num='auto', uses these values instead of rounded values.

Upvotes: 1

Related Questions