【问题标题】:Avoid Overlapping of text in scatter plot with annotations避免散点图中的文本与注释重叠
【发布时间】:2021-01-09 17:23:12
【问题描述】:

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

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();

【问题讨论】:

标签: python python-3.x pandas matplotlib


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2012-01-30
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    相关资源
    最近更新 更多