我正在练习如何使用 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
结果应该是这样的: 方形
蜘蛛网形状
但是我的结果是:
最佳答案
您需要分别拥有 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
关于python - 尝试在 matplotlib 中绘制蜘蛛网图时出现错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69376490/