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

18 投票
4 回答
47523 浏览
提问于 2025-04-16 22:18

我有一段代码可以绘制出一些点:

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

它显示的内容

但是我想要画出所有可能的线,像这样:

在这里输入图片描述

我试过使用matplotlib的路径功能,但对我来说效果不太好。

4 个回答

5

另一种方法是使用 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))
28

这个可以优化一下,但现在这样也能用:

for point in all_data:
    for point2 in all_data:
        pyplot.plot([point[0], point2[0]], [point[1], point2[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()

在这里输入图片描述

撰写回答