如何在 Matplotlib 中水平居中一個註釋,使其對齊一個點?


若要水平居中對齊註釋,以便對其一個點,我們可以採取以下步驟:

  • 使用 numpy 建立 x 和 y 的點。
  • 使用 xpoints 建立標籤。
  • 使用 scatter() 方法來分散這些點。
  • 迭代標籤、xpoints 和 ypoints,並用標籤、x 和 y 註釋該圖,使用不同的屬性,使水平對齊 ha=center。
  • 若要顯示該圖,請使用 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, 10)
ypoints = np.random.rand(10)
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='center', va='bottom',
   bbox=dict(boxstyle='round,pad=0.5', fc='green', alpha=0.5),
   arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
plt.show()

輸出

更新於: 07-May-2021

963 瀏覽量

開始你的職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.