Home > Enterprise >  Wrong result trying to plot a spider-web graph in matplotlib
Wrong result trying to plot a spider-web graph in matplotlib

Time:09-30

I am practicing how to use the matplotlib and pyplot library, and for that very reason I'm trying to make a function that plots points so that any two points have a line that connects them.

I think I'm close to solving the problem, but the result still seems a bit off.

My code is:

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

The result is supposed to look like this: Square shape

enter image description here

Spider web shape

enter image description here

My result however is:

For what is supposed to be a square shape: enter image description here

enter image description here

For what is supposed to be a spiderweb-ish shape enter image description here

CodePudding user response:

You need to have the x and y coordinates separately. The simplest would be x=[points[i][0], points[j][0]] and y=[points[i][1], points[j][1]].

Using numpy, the code could be written creating all x:

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):
    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])
    plt.axis('equal') # show squares as squares (x and y with the same distances)
    plt.show()

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

two complete graphs

  • Related