如何在 Matplotlib 中用自动放置的箭头注释散点图上的点?

matplotlibserver side programmingprogramming

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

  • 使用 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()

输出


相关文章