【问题标题】:Labeling points in matplotlib scatterplot [duplicate]matplotlib散点图中的标记点[重复]
【发布时间】:2017-12-13 08:54:13
【问题描述】:

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

我正在使用 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')

这会产生这个情节:

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

基于this SO answer我尝试使用注释来标记每个点。

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))

这会产生一个空白图。我正在密切关注另一个答案,但它没有产生任何情节。我哪里做错了?

【问题讨论】:

  • 既然您已经知道如何绘制点,并且您已经知道如何标记点,唯一悬而未决的问题是为什么带有 only 注释的绘图保持空白。这在第一个重复问题中得到了回答。对于标记点的一般情况,我添加了另一个副本。
  • @ImportanceOfBeingErnest 我不知道如何绘制标记点。我认为 .annotate() 功能可以绘制和标记点。对我来说这是有道理的,因为我指定了坐标和标签,但我错了。

标签: python matplotlib plot


【解决方案1】:

你可以这样做:

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()

【讨论】:

  • 这样效果更好,使用 .annotate() 的文本太小,所以增加大小会很有帮助
【解决方案2】:

我解决了我自己的问题。我需要绘制点然后对其进行注释,注释没有内置绘图。

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 的回答中一样

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2021-10-10
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2022-06-15
    相关资源
    最近更新 更多