12

Edit: This question is not a duplicate, I don't want to plot numbers instead of points, I wanted to plot numbers beside my points.

I'm making a plot using matplotlib. There are three points to plot [[3,9],[4,8],[5,4]]

I can easily make a scatterplot with them

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

That produces this plot:

plot

I want to label each point with numbers 1,2,3.

Based on this SO answer I tried to use annotate to label each point.

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

This produces a blank plot. I'm closely following the other answer but it isn't producing any plot. Where have I made a mistake?

Hugh
  • 413
  • 1
  • 5
  • 12
  • Since you already know how to plot points, and you already know how to label points, the only open question was why the plot with *only* annotations stays empty. This is answered in the first duplicate question. For the general case of labeling points, I added another duplicate. – ImportanceOfBeingErnest Jul 10 '17 at 10:21
  • @ImportanceOfBeingErnest I didn't know how to plot labeled points. I thought the .annotate() feature would both plot and label points. To me that made sense because I was specifying coordinates and labels, but I was wrong. – Hugh Jul 10 '17 at 10:42

2 Answers2

17

You can do that:

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

glegoux
  • 3,505
  • 15
  • 32
  • That works out better, the text using .annotate() is too small so it's helpful to be able to increase the size – Hugh Jul 09 '17 at 16:43
8

I solved my own question. I needed to plot the points and then annotate them, the annotation does not have plotting built-in.

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)

Edited to add the fontsize option just like in Gregoux's answer

Hugh
  • 413
  • 1
  • 5
  • 12