如何在 Matplotlib 中添加粗体注释文本?

matplotlibpythondata visualization更新于 2025/6/6 11:24:17

要在 matplotlib 中添加粗体注释文本,我们可以使用 LaTeX 表示标签。

步骤

  • 设置图形大小并调整子图之间和周围的填充。

  • 使用 numpy 创建 x 和 y 数据点。

  • 要为每个散点设置标签,请创建一个标签列表。

  • 使用 scatter() 方法绘制 xpoints、ypoints。对于颜色,请使用 xpoints。

  • 迭代压缩的 标签、xpoints 和 ypoints。

  • 在 for 循环中使用带有粗体 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()

输出


相关文章


有用资源