Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib does not draw the last line

I have a function that takes a list of tuples with float values, from the list I make two new separate lists, each containing the vertex coordinates of the triangle. Then I use matplotlib to draw the vertices.

def draw_figure(list_of_floats):
    
x_coord, y_coord = zip(*list_of_floats)
x_coord = list(x_coord)
y_coord = list(y_coord)

# print("Coordinates:")
# for item in x_coord:
#     print(item)
# for item in y_coord:
#     print(item)

# Plot the triangle
plt.plot(x_coord, y_coord)

# Set the plot limits
plt.xlim(min(x_coord) - 1, max(x_coord) + 1)
plt.ylim(min(y_coord) - 1, max(y_coord) + 1)

But instead of three lines, the library draws two. I tried adding:

 plt.plot(x_coord, y_coord, x_coord[0], y_coord[1]) 

So that it had to draw a third line to the beginning, but it did not work too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The image of triangle with only 2 lines

How do I supposed to fix this?

>Solution :

Just append the initial (x,y) coordinate at the end:

import matplotlib.pyplot as plt

def draw_figure(list_of_floats):
    x_coord, y_coord = zip(*list_of_floats)
    x_coord = list(x_coord)
    y_coord = list(y_coord)

    # THIS: add initial point
    x_coord.append(x_coord[0])
    y_coord.append(y_coord[0])

    # Plot the triangle
    plt.plot(x_coord, y_coord)

    # Set the plot limits
    plt.xlim(min(x_coord) - 1, max(x_coord) + 1)
    plt.ylim(min(y_coord) - 1, max(y_coord) + 1)

I tested with the following data:

draw_figure([[1, 2], [3, -1], [2.5, 5]])

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading