在Matplotlib散点图中标记数据点

12

编辑:此问题不是重复的,我不想绘制数字而不是点,我想在我的点旁边绘制数字。

我正在使用matplotlib制作图形。 有三个要绘制的点[[3,9],[4,8],[5,4]]

我可以轻松地用它们做一个散点图。

import matplotlib.pyplot as plt

allPoints = [[3,9],[4,8],[5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    xPoint =  allPoints[i][0]
    yPoint =  allPoints[i][1]
    diagram.plot(xPoint, yPoint, 'bo')

这将产生以下图表:

plot

我想用数字1、2、3标记每个点。

根据这个SO答案,我尝试使用annotate来标记每个点。

import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.annotate(pointRefNumber, (xPoint, yPoint))

这将产生一个空白的图。我紧密地遵循其他答案,但它没有产生任何图。我犯了哪个错误?


既然您已经知道如何绘制点,也知道如何标记点,那么唯一的问题是为什么只有注释的图形为空。这在第一个重复的问题中得到了解答。对于标记点的一般情况,我添加了另一个重复的问题。 - ImportanceOfBeingErnest
@ImportanceOfBeingErnest 我不知道如何绘制带标签的点。我以为 .annotate() 功能既可以绘制又可以标记点。对我来说,这很有意义,因为我正在指定坐标和标签,但我错了。 - Hugh
2个回答

17

你可以这样做:

import matplotlib.pyplot as plt

points = [[3,9],[4,8],[5,4]]

for i in range(len(points)):
    x = points[i][0]
    y = points[i][1]
    plt.plot(x, y, 'bo')
    plt.text(x * (1 + 0.01), y * (1 + 0.01) , i, fontsize=12)

plt.xlim((0, 10))
plt.ylim((0, 10))
plt.show()

scatter_plot


这样做更好,使用.annotate()的文本太小了,因此能够增加大小非常有帮助。 - Hugh

8
我解决了自己的问题。我需要先绘制点,然后注释它们,因为注释不具备绘图功能。
import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.plot(xPoint, yPoint, 'bo')
    diagram.annotate(nodeRefNumber, (xPoint, yPoint), fontsize=12)

已编辑添加了字体大小选项,就像Gregoux的答案一样


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接