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

标签 python matplotlib

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

enter image description here

关于python - 散点图螺旋向外而不是堆栈的注释 - matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29895479/

相关文章:

python - 在 Bokeh 中调整 matplotlib 标记大小?

python - NumPy 数组总和减少

python - IRichBolt 在storm-1.0.0 和 pyleus-0.3.0 上运行拓扑时出错

python - 在 K 均值聚类中组织聚类

python - 使用 matplotlib/pyplot 绘制某些内容并仅保存绘图(居中、具有相等的纵横比且没有轴或边框)

python - Matplotlib 及其与 tkinter 的连接

python - python中的动态变量名

python - 失败前提条件错误: Attempting to use uninitialized value conv2d_1/kernel with Tensorflow/Python

python - 如何在 python 中创建两个不同大小的样本之间的 qq 图?

python - 散点图的轴限制 - Matplotlib