如何在Matplotlib中使用一个文本标注多个点?

如何在Matplotlib中使用一个文本标注多个点?

为了在Matplotlib中为多个点添加注释文本,我们可以执行以下操作-

  • 设置图形大小并调整子图之间和周围的填充。
  • 使用numpy创建x和y数据点。
  • 为每个散点设置标签,请制作标签列表。
  • 使用 scatter() 方法绘制xpoints, ypoints。对于颜色,使用xpoints。
  • 迭代zipped标签,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()

输出

如何在Matplotlib中使用一个文本标注多个点?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程