How to draw a triangle using matplotlib.pyplot based on 3 dots (x,y) in 2D?

家住魔仙堡 提交于 2019-11-29 22:57:56

问题


I would like to draw a triangle using python3 module matplotlib.

import numpy as np 
import matplotlib.pyplot as plt

X_train = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y_train = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X_train[:, 0], X_train[:, 1], s = 170, color = Y_train[:])
plt.show()

It displays 6 dots but they are grouped separately in 2 places. (color helps to see it clearly)

There are 2 sets of 3 dots. I want each set(3 dots) be united in the triangle.

How is it possible to implement this? How to build a triangle based on 3 dots using matplotlib?

Any suggestions are appreciated ;)


回答1:


A triangle is a polygon. You may use plt.Polygon to draw a polygon.

import numpy as np 
import matplotlib.pyplot as plt

X = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X[:, 0], X[:, 1], s = 170, color = Y[:])

t1 = plt.Polygon(X[:3,:], color=Y[0])
plt.gca().add_patch(t1)

t2 = plt.Polygon(X[3:6,:], color=Y[3])
plt.gca().add_patch(t2)

plt.show()



来源:https://stackoverflow.com/questions/44397105/how-to-draw-a-triangle-using-matplotlib-pyplot-based-on-3-dots-x-y-in-2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!