避免散点图中的文本与注释重叠

时间:2021-01-09 17:23:12

标签: python python-3.x pandas matplotlib

如何避免下图中的文字重叠?我的上散点图点非常接近,但看起来,如果我尝试任何东西,它不会改变任何东西,是否有任何解决方法。

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

1 个答案:

答案 0 :(得分: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))