如何在 Matplotlib 中用一个文本注释多个点?
matplotlibpythondata visualization更新于 2025/9/12 15:08:17
要在 Matplotlib 中为多个点添加带注释的文本,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 使用 numpy 创建 x 和 y 数据点。
- 要为每个散点设置标签,请制作一个标签列表。
- 使用 scatter() 方法绘制 xpoints、ypoints。对于颜色,请使用 xpoints。
- 迭代压缩的标签、xpoints 和 ypoints。
- 在 for 循环中使用 annotate() 方法和粗体 LaTeX 表示。
- 要显示图形,请使用 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()
输出


相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

