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

标签 python numpy matplotlib plot graph

我正在练习如何使用 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

最佳答案

您需要分别拥有 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

关于python - 尝试在 matplotlib 中绘制蜘蛛网图时出现错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69376490/

相关文章:

python - 是否有等同于 np.empty 的 tensorflow ?

matplotlib - 如何根据分类输入变量可视化(绘制)回归输出?

python - 向 matplotlib 颜色条添加刻度

python - 如何使用 NLTK BigramAssocMeasures.ch_sq

python - 终止后从 tcpdump 子进程获取 stdout

python - PuLP 输出到 numpy 数组

python - 保存 matplotlib.animation 输出 0 秒视频

Python打开原始音频数据文件

python - 无法在 Windows 中使用 solr、haystack 和 django 创建索引文件

python - 使用 numpy.unravel_index