Python:在每个数据点处具有对齐注释的散点图

时间:2015-03-24 13:16:55

标签: python matplotlib plot label scatter-plot

我想制作一个带有几十个点的散点图,这些点可能彼此非常接近。我从问题的答案中尝试了注释方法:

>> matplotlib scatter plot with different text at each data point

但是当点彼此足够接近时,您可以看到标签/注释重叠。是否有任何库或方法来生成这样的图,其中各个注释不会相互冲突,也不会与图的边界发生冲突?

import matplotlib.pyplot as plt

z = [0.15, 0.3, 0.45, 0.46, 0.6, 0.75]
y = [2.56422, 3.77284, 3.52623, 3.52623, 3.51468, 3.02199]
n = [58, 651, 393, "393(2)", 203, 123]

fig, ax = plt.subplots()
ax.scatter( z, y )

for i, txt in enumerate( n ):
    ax.annotate( txt, ( z[i] + .01, y[i] + .01 ) )

plt.show()
Scatter plot with colliding annotations

1 个答案:

答案 0 :(得分:5)

我已经写了一个库adjustText来完成这个。 https://github.com/Phlya/adjustText

z = [0.15, 0.3, 0.45, 0.46, 0.6, 0.75]
y = [2.56422, 3.77284, 3.52623, 3.52623, 3.51468, 3.02199]
n = [58, 651, 393, "393(2)", 203, 123]

fig, ax = plt.subplots()
ax.scatter( z, y )
texts = []
for i, txt in enumerate( n ):
    texts.append(ax.text(z[i], y[i], txt))
adjust_text(texts)
plt.show()

enter image description here