0

In the pyplot below, many of the items occupy a very similar spot, so that the annotations overlap. I moved the annotations a random distance away from each item but that looks strange in sparse areas and still isn't enough in dense areas. I could implement some kind of spring based physics layout to prevent labels from colliding but that seems like overengineering for such a simple problem. Is there any existing mechanism to prevent item labels from overlapping?

def randompoint():
    deg = 2 * math.pi * random.random()
    R = 80
    return (math.cos(deg)*R,math.sin(deg)*R)

for i in range(len(D)):
    plt.annotate(items[i]["label"], xy=data[i],xytext=randompoint(),textcoords="offset points", arrowprops=dict(facecolor='black', shrink=0.05, width=0.01, headwidth=0.01))

pyplot with overlapping labels

Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118
  • 1
    There is a [adjusttext library](https://adjusttext.readthedocs.io/en/latest/Examples.html) that automatically adjusts the display values so that the annotations do not overlap. It may take a little longer to run, but I personally think it works well. – r-beginners Aug 17 '21 at 14:43
  • @r-beginners: Thanks for the link! However I do not understand where this `texts` array comes from in the documentation of the adjusttext library, do you know how to use it in my use case with `plt.annotate()`? – Konrad Höffner Aug 17 '21 at 15:18
  • @r-beginners: OK I rewrote my code now to use `text()` instead of `annotate()` and it works, thanks! However it is extremely slow even with just 25 points. – Konrad Höffner Aug 17 '21 at 15:24

0 Answers0