尝试在matplotlib中绘制蜘蛛网图时出现错误结果

2024-06-02 06:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在练习如何使用matplotlib和pyplot库,正是出于这个原因,我正在尝试制作一个函数来绘制点,使任意两点都有一条 连接它们

我想我快要解决这个问题了,但结果似乎还是有点不对劲

我的代码是:

import numpy as np
import matplotlib.pyplot as plt

alpha = (np.sqrt(2)/2)
square_points = ((0, 0),(1, 0),(0, 1),(1, 1))
shape_points = ((1, 0),(alpha, alpha),(0, 1),(-alpha, alpha),(-1, 0),(-alpha, -alpha),(0, -1),(alpha, -alpha))


def complete_graph(points):
    for i in range(len(points)):
        for j in range(i):
            x = (points[i])
            y = (points[j])
            plt.plot(x, y)
    plt.show()

complete_graph(square_points)   #square shape
complete_graph(shape_points)    #spider web ish shape

结果应该是这样的: 方形

enter image description here

蜘蛛网形状

enter image description here

然而,我的结果是:

对于应该是正方形的形状:enter image description here

enter image description here

应该是蜘蛛网状的形状enter image description here


1条回答
网友
1楼 · 发布于 2024-06-02 06:28:37

你需要分别得到x和y坐标。最简单的是x=[points[i][0], points[j][0]]y=[points[i][1], points[j][1]]

使用numpy,可以编写创建所有x的代码。可以使用plt.scatter()绘制顶点。将z顺序设置为3会在边的前面显示它们

import numpy as np
import matplotlib.pyplot as plt

alpha = np.sqrt(2) / 2
square_points = ((0, 0), (1, 0), (0, 1), (1, 1))
shape_points = ((1, 0), (alpha, alpha), (0, 1), (-alpha, alpha), (-1, 0), (-alpha, -alpha), (0, -1), (alpha, -alpha))

def complete_graph(points):
    # calculate and plot the edges
    edges = np.array([(points[i], points[j]) for i in range(len(points)) for j in range(i)]).reshape(-1, 2)
    plt.plot(edges[:, 0], edges[:, 1], color='dodgerblue')
    points = np.array(points)
    # plot the vertices
    plt.scatter(points[:, 0], points[:, 1], color='mediumvioletred', s=100, zorder=3)
    plt.axis('equal')  # show squares as squares (x and y with the same distances)
    plt.axis('off')  # hide the surrounding rectangle and ticks
    plt.show()

complete_graph(square_points)  # square shape
complete_graph(shape_points)  # spider web ish shape

two complete graphs

相关问题 更多 >