George
George

Reputation: 1175

How do you create line segments between two points?

I have this bit of code that plots out the points:

import matplotlib.pyplot as plot
from matplotlib import pyplot

all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
x = []
y = []
for i in xrange(len(all_data)):
    x.append(all_data[i][0])
    y.append(all_data[i][1])
plot.scatter(x,y)

pyplot.show()

what it shows

but I want all the possible lines that could be made that looks something like this:

enter image description here

I've tried matplotlib path, but it doesn't work well for me.

Upvotes: 19

Views: 48037

Answers (4)

wallE
wallE

Reputation: 61

One other way could be to use matplotlib patches

import matplotlib
import pylab as pl
fig, ax = pl.subplots()
import matplotlib.patches as patches
from matplotlib.path import Path

verts = [(x1,y1), (x2,y2)]
codes = [Path.MOVETO,Path.LINETO]
path = Path(verts, codes)
ax.add_patch(patches.PathPatch(path, color='green', lw=0.5))

Upvotes: 5

unutbu
unutbu

Reputation: 879113

import matplotlib.pyplot as plt
import itertools 

fig=plt.figure()
ax=fig.add_subplot(111)
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
plt.plot(
    *zip(*itertools.chain.from_iterable(itertools.combinations(all_data, 2))),
    color = 'brown', marker = 'o')

plt.show()

enter image description here

Upvotes: 23

joaquin
joaquin

Reputation: 85615

This can be optimized but it works:

for point in all_data:
    for point2 in all_data:
        pyplot.plot([point[0], point2[0]], [point[1], point2[1]])

enter image description here

Upvotes: 28

fransua
fransua

Reputation: 1608

using all combinations?

import matplotlib.pyplot as plot
from matplotlib import pyplot

all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
x = []
y = []
for i in combinations(all_data,2):
    x.extend(i[0])
    y.extend(i[1])

plot.plot(x,y)
pyplot.show()

Upvotes: 4

Related Questions