The Python Oracle

Plotting a list of (x, y) coordinates in matplotlib

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping

--

Chapters
00:00 Plotting A List Of (X, Y) Coordinates In Matplotlib
01:10 Accepted Answer Score 272
01:41 Answer 2 Score 13
01:58 Answer 3 Score 71
02:09 Thank you

--

Full question
https://stackoverflow.com/questions/2151...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #plot #coordinates

#avk47



ACCEPTED ANSWER

Score 272


Given li in the question:

li = list(zip(range(1, 14), range(14, 27)))

To unpack the data from pairs into lists use zip:

x, y = zip(*li)

x → (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
y → (14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)

The one-liner uses the unpacking operator (*), to unpack the list of tuples for zip, and unpacks the zip object into the plot API.

plt.scatter(*zip(*li))

enter image description here

plt.plot(*zip(*li))

enter image description here




ANSWER 2

Score 71


If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()



ANSWER 3

Score 13


If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.