python - matplotlib 中的 "Repel"注释?

标签 python matplotlib plot

我最近看到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()

enter image description here

您可以看到,当数据密度很高时,即使是这么短的标签也会造成困惑。

最佳答案

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

enter image description here

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

enter image description here

关于python - matplotlib 中的 "Repel"注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693991/

相关文章:

python - 值错误: matmul when trying to fit sklearn's linear regressor to pandas dataframe instanses

python - 用 Pandas 替换数据框中不同列的值

python 从 matplotlib click 返回 ydata

r - 如何使用 R 在一个图中绘制多个物种积累曲线

python - 有没有办法找出哪个 Python 方法可以引发哪个异常或错误

python - matplotlib Axis 值未排序

python - 如何绘制多个 Pandas 列

r - ggplot2无法绘制曲线

python - 如何沿曲线注释文本

python - 给定边缘拆分 DataFrame 的最佳方法