如何在两点之间创建线段?

时间:2011-07-26 18:08:07

标签: python matplotlib

我有一些代码来绘制点:

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

但是我希望所有可能的行看起来像这样:

enter image description here

我尝试了matplotlib路径,但它对我来说效果不佳。

4 个答案:

答案 0 :(得分:26)

这可以优化但是有效:

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

enter image description here

答案 1 :(得分:23)

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

答案 2 :(得分:4)

使用所有组合?

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

答案 3 :(得分:3)

另一种方法可能是使用matplotlib补丁

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