迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Matplotlib 标记散点

作者:迹忆客 最近更新:2023/03/17 浏览次数:

为了给 Matplotlib 中的散点图标记散点,我们可以使用 matplotlib.pyplot.annotate() 函数,在指定的位置添加一个字符串。同样,我们也可以使用 matplotlib.pyplot.text() 函数为散点图点添加文字标签。

使用 matplotlib.pyplot.annotate() 函数为散点图点添加标签

matplotlib.pyplot.annotate(text,
                           xy, 
                           *args, 
                           **kwargs)

它用 text 参数的值对点 xy 进行注释。xy 代表要注释的点的坐标 (x, y)

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.annotate(label, (X[i], Y[i]))

plt.show()

输出:

使用 matplotlib.pyplot.annotate()函数为散点图添加标签

它创建了两个随机数组,XY,分别代表点的 X 坐标和 Y 坐标。我们有一个名为 annotations 的列表,长度与 XY 相同,其中包含每个点的标签。最后,我们通过循环迭代,使用 annotate() 方法为散点图中的每个点添加标签。

使用 matplotlib.pyplot.text() 函数为散点图点添加标签

matplotlib.pyplot.text(x,
                       y,
                       s, 
                       fontdict=None,
                       **kwargs)

这里,xy 代表我们需要放置文字的坐标,s 是需要添加的文字内容。

该函数在 xy 指定的点上添加文字 s,其中 x 代表该点的 X 坐标,y 代表 Y 坐标。

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(20)

X=np.random.randint(10, size=(5))
Y=np.random.randint(10, size=(5))

annotations=["Point-1","Point-2","Point-3","Point-4","Point-5"]

plt.figure(figsize=(8,6))
plt.scatter(X,Y,s=100,color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with annotations",fontsize=15)
for i, label in enumerate(annotations):
    plt.text(X[i], Y[i],label)

plt.show()

输出:

使用 matplotlib.pyplot.text()函数为散点图添加标签

它通过循环执行,使用 matplotlib.pyplot.text() 方法为散点图中的每个点添加标签。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便