如何在 Matplotlib 中使用一段文字對多個點進行註釋?
若要在 Matplotlib 中為多個點新增帶註釋的文字,我們可以採取以下步驟 -
- 設定圖形大小並調整子圖之間的內邊距。
- 使用 numpy 建立 x 和 y 資料點。
- 建立一個標籤列表,用於設定每個散點圖的標籤。
- 使用**scatter()**方法繪製 xpoints、ypoints。對於顏色,使用 xpoints。
- 迭代拉鍊標籤、xpoints 和 ypoints。
- 在迴圈中使用帶有加粗 LaTeX 表示形式的 annotate() 方法。
- 使用**show()**方法顯示圖形。
示例
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 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( f"$\bf{label}$", xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='center', va='bottom', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) plt.show()
輸出
廣告