1

How can I avoid overlapping text in the following image? My upper scatter plot points are very closer, but it looks like, if I try anything, it doesn't change anything, Is there any work around for the same.

plt.figure(figsize=(17,15), dpi= 300)
plt.style.use('fivethirtyeight')
colors = cm.rainbow(np.linspace(0, 1, 158))
ax = plt.scatter(merged_latest['HDI'], merged_latest['electricity_access'], s=merged_latest['HDI'],c = colors,  alpha=0.1, cmap = plt.get_cmap('Spectral'))
plt.ylabel('Electricity Access')
plt.xlabel('HDI')
plt.title('Electricity Access versus HDI')

old_x = old_y = 1e9 # make an impossibly large initial offset
thresh = .1 #make a distance threshold

for label, x, y in zip(list(merged_latest['Country Name']), merged_latest['HDI'], merged_latest['electricity_access']):
    #calculate distance
    d = ((x-old_x)**2+(y-old_y)**2)**(.5)

    #if distance less than thresh then flip the arrow
    flip = 1
    if d < .1: flip=-2

    plt.annotate(
        label,
        xy = (x, y), xytext = (-20*flip, 20*flip),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.9),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    old_x = x
    old_y = y
    
plt.tight_layout()
plt.show();

matplotlib

Mr. T
  • 11,960
  • 10
  • 32
  • 54
  • 1
    Your best bet is to use the adjustText library mentioned in this thread: [Matplotlib overlapping annotations / text](https://stackoverflow.com/questions/19073683/matplotlib-overlapping-annotations-text) – Mr. T Jan 09 '21 at 17:30
  • Can you please suggest, how can it fit to my case. – WholewayOCdes Jan 09 '21 at 17:33

1 Answers1

0
from adjustText import adjust_text

texts = []
for x, y, s in zip(merged_latest['Population Growth'], merged_latest['GDP per capita'], merged_latest['Country Name']):
    texts.append(plt.text(x, y, s))
adjust_text(texts, only_move={'points':'y', 'texts':'y'}, arrowprops=dict(arrowstyle="->", color='r', lw=0.5))