我最近看到this R/ggplot2 的包,它允许一个人在一个图上有多个注释并自动调整它们的位置以最小化重叠,这样可以提高可读性。有没有什么 类似的可用于 python/matplotlib?
编辑: 我找到了 Matplotlib overlapping annotations / text看起来很有希望,但结果似乎不如 R 包。
例子:
from matplotlib import pyplot as plt
import numpy as np
xs = np.arange(10, step=0.1)+np.random.random(100)*3
ys = np.arange(10, step=0.1)+np.random.random(100)*3
labels = np.arange(100)
plt.scatter(xs, ys)
for x, y, s in zip(xs, ys, labels):
plt.text(x, y, s)
plt.show()
您可以看到,当数据密度很高时,即使是这么短的标签也会造成困惑。
最佳答案
[12-11-2016 再次更新了代码和第二张图,因为此后库有了显着改进]
答案完全重写
我为此创建了一个小型库,其工作方式与上述 ggrepel 类似:https://github.com/Phlya/adjustText
关闭点的排斥,即使对于这个困难的例子,它也会产生一些不错的东西:
from matplotlib import pyplot as plt
from adjustText import adjust_text
import numpy as np
np.random.seed(2016)
xs = np.arange(10, step=0.1) + np.random.random(100) * 3
ys = np.arange(10, step=0.1) + np.random.random(100) * 3
labels = np.arange(100)
f = plt.figure()
scatter = plt.scatter(xs, ys, s=15, c='r', edgecolors='w')
texts = []
for x, y, s in zip(xs, ys, labels):
texts.append(plt.text(x, y, s))
plt.show()
adjust_text(texts, force_points=0.2, force_text=0.2,
expand_points=(1, 1), expand_text=(1, 1),
arrowprops=dict(arrowstyle="-", color='black', lw=0.5))
plt.show()
关于python - matplotlib 中的 "Repel"注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693991/