简体   繁体   中英

How to get matplotlib to connect all scatter points?

I want to connect 3 points so it forms a triangle. I tried 2 approaches:

One was using plot to draw a line between each of the 3 points (point 1 to point 2, 2 to 3, and 3 to 1), but the lines weren't ending up where I expected so I have them in my code snippet below commented out. The first line would plot fine, but the subsequent ones were off. I checked the logic several times and it seems right. Perhaps there is some matplotlib quirk I'm unaware of.

The other approach was using scatter and finding a way to simply connect all the points, but I can't find any method or simple way to do this. The points plot fine, I just can't connect them. Here is my code snippet (z is a list of 6 elements for the 3 points x1, y1, x2, y2, x3, y3):

def display_triangle(z):
import matplotlib.pyplot as plt

x_values = [z[0], z[2], z[4]]
y_values = [z[1], z[3], z[5]]
plt.scatter(x_values, y_values)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.show()

#point_1 = [x_values[0], y_values[0]]
#point_2 = [x_values[1], y_values[1]]
#point_3 = [x_values[2], y_values[2]]
#plt.plot(point_1,point_3, 'ro-')
#plt.plot(point_3,point_1, 'ro-')
#plt.plot(point_1,point_2, 'ro-')
#plt.plot(x_values, y_values)
import matplotlib.pyplot as plt
x_values = [0, 0, 4, 0]
y_values = [0, 3, 0, 0]
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.plot(x_values,y_values, 'ro-')
plt.show()

this draws from 0,0 to 0,3 to 4,0 and back to 0,0 to close triangle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM