Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Annotate at the top of a marker with varying sizes in matplotlib

Can I get the coordinates of markers to move the annotation to the top of the triangle?

import matplotlib.pyplot as plt

X = [1,2,3,4,5]
Y = [1,1,1,1,1]
labels = 'ABCDE'
sizes = [1000, 1500, 2000, 2500, 3000]

fig, ax = plt.subplots()

ax.scatter(X, Y, s= sizes, marker = 10)

for x, y, label, size in zip(X, Y, labels, sizes):
    print(x,y)
    ax.annotate(label, (x, y), fontsize=12)

plt.show()

Which gives me:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to (a) move the y coordinate by something proportional to the height of the marker; (b) root the text at bottom centre ("center" in American!).

Note that the "size" of a marker is proportional to its AREA. So its height is proportional to sqrt(size).

A certain amount of trial and error produced this. The height scaling probably depends on the type of marker.

import math
import matplotlib.pyplot as plt

X = [1,2,3,4,5]
Y = [1,1,1,1,1]
labels = 'ABCDE'
sizes = [1000, 1500, 2000, 2500, 3000]

fig, ax = plt.subplots()

ax.scatter(X, Y, s= sizes, marker = 10)

for x, y, label, size in zip(X, Y, labels, sizes):
    print(x,y,size)
    ax.annotate(label, (x, y + math.sqrt( size ) / 3000 ), horizontalalignment='center', fontsize=12)

plt.show()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading