Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

python - Avoid Overlapping of text in scatter plot with annotations

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

question from:https://stackoverflow.com/questions/65645497/avoid-overlapping-of-text-in-scatter-plot-with-annotations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...