2017-04-04 57 views
1

我曾嘗試以下生產正多邊形,使在python梯形,平行四邊形:如何使用matplotlib

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111, aspect='equal') 
ax2.add_patch(
    patches.RegularPolygon(
     (0.5, 0.5), 
     3, 
     0.2, 
     fill=False  # remove background 
    ) 
) 

fig2.savefig('reg-polygon.png', dpi=90, bbox_inches='tight') 
plt.show() 

雖然這會產生一個三角形,我還沒有發現任何方式產生梯形並和平行四邊形
是否有任何命令來做到這一點?或者我可以將正多邊形轉換爲其他形狀之一嗎?

+1

什麼是錯誤? – ABcDexter

+0

它給我的長方形身材 –

+0

是的,這似乎是這樣,我尋找到它。 – ABcDexter

回答

2

你可能會需要使用matplotlib.patches.Polygon和你自己定義的角落。

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 

fig = plt.figure() 
ax = fig.add_subplot(111, aspect='equal') 

# Parallelogram 
x = [0.3,0.6,.7,.4] 
y = [0.4,0.4,0.6,0.6] 
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=False)) 

# Trapez 
x = [0.3,0.6,.5,.4] 
y = [0.7,0.7,0.9,0.9] 
ax.add_patch(patches.Polygon(xy=list(zip(x,y)), fill=False)) 

plt.show() 

enter image description here

+1

在Python3中,你需要'list(zip(x,y))'而不是'zip(x,y)'。 –

1

一個簡單的方法來做到這一點是創建列表的多邊形(平行四邊形/梯形)和繪圖(或者更確切地說,跟蹤),它們的端點的列表。

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
fig2 = plt.figure() 
ax2 = fig2.add_subplot(111, aspect='equal') 

points = [[0.2, 0.4], [0.4, 0.8], [0.8, 0.8], [0.6, 0.4], [0.2,0.4]] #the points to trace the edges. 
polygon= plt.Polygon(points, fill=None, edgecolor='r') 
ax2.add_patch(polygon) 
fig2.savefig('reg-polygon.png', dpi=90, bbox_inches='tight') 
plt.show() 

另外請注意,您應該使用Polygon而不是RegularPolygon

+1

Thankyou ...... @ ABcDexter –

+0

歡迎您:)如果您對答案滿意,請立即投訴並將其標記爲已接受。 @VikasBhargav – ABcDexter