Boris Kalinin
Boris Kalinin

Reputation: 134

matplotlib legend element sizes do not correspond to the values given in func

I have a matplotlib scatter plot, where points sizes are logarithmically connected to points values. I would like to create a legend for this plot and I try to do that with the code:

x = df['A']
y = df['B']
colors = df['C']
sizes = np.log10(0.1 * df['C']) / np.log10(1.03)

plt.figure(figsize=(5,5))
dots = plt.scatter(x, y, s=sizes, c=colors, alpha=0.5)
plt.xlim(-0.005, 0.145)
plt.ylim(0, 0.06)
plt.legend(*dots.legend_elements('sizes', num=4, func=lambda x: np.power(1.03, x)))
plt.show()

Expected behavior:

I expect to see four lines in my legend where sizes of legend elements are the same as the according sizes of points on my plot.

If I remove the func argument from the dots.legend_elements method I get 4 lines in my legend. But I also want them to have correct values after the elements.

enter image description here

Reality:

I see only three lines and legend elements are not the same as the sizes in my sizes array.

enter image description here

My func argument seems to be the inverse of the np.log10(0.1 * x) / np.log10(1.03) but probably I'm using it wrong.

Upvotes: 0

Views: 143

Answers (1)

ombk
ombk

Reputation: 2111

Solution

func=lambda x: 10**(np.log10(1.03)*x+1)

Example

sizes = np.log10(0.1 * 50) / np.log10(1.03)
#output 54.44868500700143
func(sizes)
#output 49.99999999999999

This should do the trick.

Upvotes: 1

Related Questions