Python matplotlib anotate overlaping points

Viewed 24

I have a situation where I need to plot a list of points where they can overlap. The problem is that the Point label are overlapping, and I need to identify which point is where.

having sample code:

import matplotlib.pyplot as plt

Nu = [6.0155, 12.031, 12.031, 12.031, 12.031]
Ra = [40.22, 40.66, 40.66, 40.66, 40.66]

P = ["P_1", "P_2", "P_3", "P_4", "P_5"]
fig, ax = plt.subplots()
plt.scatter(Ra, Nu)
for i, txt in enumerate(P):
    plt.annotate(txt, (Ra[i], Nu[i]))

Got this result:

enter image description here

Where 5 points and annotations are overlapping in top right corner.

1 Answers

I supose you have use those identical coordinates to over exagerate your example. If that is the case there is a nice package that can hep you to adapt annotations in matplotlib.

package https://pypi.org/project/adjustText/

documentation https://adjusttext.readthedocs.io/en/latest/

I know it works good using plt.text instead of plt.annotate

import matplotlib.pyplot as plt
from adjustText import adjust_text


Nu = [6.0155, 12.031, 12.031, 12.031, 12.031]
Ra = [40.22, 40.66, 40.66, 40.66, 40.66]

P = ["P_1", "P_2", "P_3", "P_4", "P_5"]
fig, ax = plt.subplots()
plt.scatter(Ra, Nu)
texts = [plt.text(Ra[i], Nu[i], txt,size=16) for i, txt in enumerate(P)]
adjust_text(texts, arrowprops=dict(arrowstyle="->", color='r'))

The output is enter image description here

Related