This SO question提供了一些帮助,以防止注释相互重叠,但它只是向上堆叠注释,而不是使其尽可能接近其应有的 (x,y) 位置。现在它只是将东西直接堆叠到原始 x,y 位置毫无意义的位置。
相关部分是这样的:
def get_text_positions(x_data, y_data, txt_width, txt_height):
a = zip(y_data, x_data)
text_positions = y_data.copy()
for index, (y, x) in enumerate(a):
local_text_positions = [i for i in a if i[0] > (y - txt_height)
and (abs(i[1] - x) < txt_width * 2) and i != (y,x)]
if local_text_positions:
sorted_ltp = sorted(local_text_positions)
if abs(sorted_ltp[0][0] - y) < txt_height: #True == collision
differ = np.diff(sorted_ltp, axis=0)
a[index] = (sorted_ltp[-1][0] + txt_height, a[index][1])
text_positions[index] = sorted_ltp[-1][0] + txt_height
for k, (j, m) in enumerate(differ):
#j is the vertical distance between words
if j > txt_height * 2: #if True then room to fit a word in
a[index] = (sorted_ltp[k][0] + txt_height, a[index][1])
text_positions[index] = sorted_ltp[k][0] + txt_height
break
return text_positions
我认为魔法发生在 j > txt_height
行,但如果有重叠,我想开始左右移动东西。
编辑:我没有调整外部 for 循环中的任何内容,因为它看起来正在计算是否有任何文本位置位于同一“邻居”中。 if local_text_positions: 如果其中任何一个重叠,则运行。 np.diff 正在采取一阶差异...但我不知道 j>txt_height 之后发生了什么,就像我在问题中提到的那样。
最佳答案
查看我的库,它是这样做的: https://github.com/Phlya/adjustText
import matplotlib.pyplot as plt
from adjustText import adjust_text
import numpy as np
np.random.seed(2016)
N = 50
scatter_data = np.random.rand(N, 3)
fig, ax = plt.subplots()
bubbles = ax.scatter(scatter_data[:, 0], scatter_data[:, 1],
c=scatter_data[:, 2], s=scatter_data[:, 2] * 150)
labels = ['ano_{}'.format(i) for i in range(N)]
texts = []
for x, y, text in zip(scatter_data[:, 0], scatter_data[:, 1], labels):
texts.append(ax.text(x, y, text))
adjust_text(texts, force_text=0.05, arrowprops=dict(arrowstyle="-|>",
color='r', alpha=0.5))
plt.show()
关于python - 散点图螺旋向外而不是堆栈的注释 - matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29895479/