如何在带有 Matplotlib 中自动放置箭头的散点图上进行注释?


要使用自动放置的箭头对散点图上的点进行注释,我们可以采取以下步骤 -

  • 使用 numpy 创建 x 和 y 的点。

  • 使用xpoints创建标签。

  • 使用 scatter() 方法散射点。

  • 迭代标签、xpoints 和 ypoints,并用不同的属性注释标签、x 和 y。

  • 要显示图形,请使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xpoints = np.linspace(1, 10, 25)
ypoints = np.random.rand(25)
labels = ["%.2f" % i for i in xpoints]
plt.scatter(xpoints, ypoints, c=xpoints)
for label, x, y in zip(labels, xpoints, ypoints):
   plt.annotate(
      label,
      xy=(x, y), xytext=(-20, 20),
      textcoords='offset points', ha='right', va='bottom',
      bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
      arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
   )
plt.show()

输出

更新于: 2021 年 5 月 8 日

1K+ 次浏览

开启您的事业

完成课程获得认证

开始使用
广告
© . All rights reserved.