散点图螺旋向外而不是堆栈matplotlib的注释

2024-06-08 03:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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.差异取一阶差。。。但我不知道我在问题中提到的j>;txt峎高之后会发生什么。在


Tags: andtextintxtfordataindexif
1条回答
网友
1楼 · 发布于 2024-06-08 03:59:52

我的图书馆是哪家的: 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()

enter image description here

相关问题 更多 >

    热门问题