如何在帶有 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.