Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot Numbers Instead of Points Using Matplotlib Scatterplot

I'm trying to plot a scatterplot, but instead of having points or triangles or other symbols, I want to plot numbers. For example, with these points:

centroidCoords = [Point(7.210123936676805, -0.0014481952154823),
                  Point(5.817327756517152, -1.0513260084561042),
                  Point(5.603133733696165, -2.7765635631249412),
                  Point(4.500525247710033, -0.8659667639805515),
                  Point(3.9999999999880367, -2.089987631283091),

I can plot in a scatterplot like:

# xs = [point.x for point in centroidCoords]
# ys = [point.y for point in centroidCoords]
# plt.scatter(xs, ys)

But instead of the little circular points, I'm wondering if I can plot numbers. The first point could be 1, the second point 2, etc. I tried using zip to assign the numbers like so:

num_label = range(0,len(centroidCoords),1)
numberedCentroids = zip(centroidCoords, num_label)
print(numberedCentroids)

but it doesn't print or plot how I imagined. All I want is a plot with the number 1 at point 1 coordinates, the number 2 at point 2 coordinates, etc. Eventually I will add polygons in the back and this is going to look like one of those "color the number" things.

I'm pretty new to python, so any help would be greatly appreciated!

like image 473
Doda Avatar asked Mar 03 '26 12:03

Doda


2 Answers

Matplotlib's documentation says that plt.scatter has a parameter called "marker" that defines what is used as 'points' on the plots, but it is going to be the same for all the data plotted with the same command. So I guess if you want it changed for every coordinate pair, you could do:

for i in range(len(centroidCoords)):
    plt.scatter(centroidCoords[i].x,centroidCoords[i].y, marker="$"+str(i)+"$")

Dollar signs are necessary, so that it renders then number as regular text.

like image 120
bakhtos Avatar answered Mar 05 '26 02:03

bakhtos


You can just plot text anywhere you want, but you have to set the limits of the image manually by calling .xlim() and .ylim()

import numpy as np
import matplotlib.pyplot as plt

centroidCoords = [(7.210123936676805, -0.0014481952154823),
                  (5.817327756517152, -1.0513260084561042),
                  (5.603133733696165, -2.7765635631249412),
                  (4.500525247710033, -0.8659667639805515),
                  (3.9999999999880367, -2.089987631283091)]

textCoord = [f"{x:.2f} {y:.2f}" for x, y in centroidCoords]
x, y = np.array(centroidCoords).T

for col, row, t in zip(x, y, textCoord):
    plt.text(col, row, t, fontsize=10, color="red")
plt.xlim(min(x)-1, max(x)+1)
plt.ylim(min(y)-1, max(y)+1)
plt.show()

enter image description here

like image 21
Colim Avatar answered Mar 05 '26 03:03

Colim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!