2014-01-09 74 views
3

我試圖在python中繪製2D矩形板。該板將被拆分成可變數量的部分,這些部分中的每一個都將填充陰影圖案。該陰影圖案將具有指定的角度。下面顯示了一個包含5個部分的矩形和其截面剖面線方向(度數)爲[0,45,0,-45,0]的數組的示例。這將需要能夠顯示任何方向,而不是隻是一般的90,45,0,即33,74.5等在Python中繪製不同角度的填充矩形

enter image description here

任何想法,我怎麼能做到這一點?從本質上講,我只是想在每個部分中展示方向,其他表達相同結果的方法將非常值得讚賞,例如一條線代替陰影線。

編輯(問題回答後): Greg提供的編輯腳本如下所示。

from numpy import cos, sin 
import numpy as np 
import matplotlib.pyplot as plt 

angles = [0,10,20,30,40,50] 

numberOfSections = len(angles) 

def plot_hatches(ax, angle, offset=.1): 
    angle_radians = np.radians(angle) 
    x = np.linspace(-1, 1, 10) 
    for c in np.arange(-2, 2, offset): 
     yprime = cos(angle_radians) * c - sin(angle_radians) * x 
     xprime = sin(angle_radians) * c + cos(angle_radians) * x 
     ax.plot(xprime, yprime, color="b", linewidth=2) 
    ax.set_ylim(0, 1) 
    ax.set_xlim(0, 1) 
    return ax 

fig, axes = plt.subplots(nrows=1, ncols=numberOfSections, figsize=(16,(16/numberOfSections)), sharex=True, sharey=True) 

for i in range(len(axes.flat)): 
    plot_hatches(axes.flat[i], angles[i]) 

fig.subplots_adjust(hspace=0, wspace=0) 
plt.show() 

產生如下圖所示。 enter image description here 但檢查時角度與輸入角度不匹配。

回答

3

我有一個基本的想法,雖然我懷疑你需要做更多的取決於你想要結果如何靈活。

from numpy import cos, sin 
import numpy as np 
import matplotlib.pyplot as plt 

def plot_hatches(ax, angle, offset=.1): 
    angle_radians = np.radians(angle) 
    x = np.linspace(-2, 2, 10) 
    for c in np.arange(-2, 2, offset): 
     yprime = cos(angle_radians) * c + sin(angle_radians) * x 
     xprime = sin(angle_radians) * c - cos(angle_radians) * x 
     ax.plot(xprime, yprime, color="k") 
    ax.set_ylim(0, 1) 
    ax.set_xlim(0, 1) 
    return ax 


fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8,8), sharex=True, sharey=True) 

for i in range(len(axes.flat)): 
    plot_hatches(axes.flat[i], np.random.uniform(0, 90)) 

fig.subplots_adjust(hspace=0, wspace=0) 

有兩組事情在這裏的部分:首先是功能plot_hatches其在座標軸上ax單位正方形平艙口。這是通過採用一行x, y=c並使用rotation matrix旋轉它來獲得xprimeyprime,它們是與x軸成角度的線的座標,偏移量爲c。遍歷c的幾個值覆蓋單位正方形,可以通過使offset參數更小來使行更加密集。其次我們需要一種方法來繪製彼此相鄰的座標軸。這我已經使用subplots。這返回fig, axesaxes是一個軸實例數組,所以我們遍歷它們將它們傳遞給函數來繪製陰影並每次給它一個隨機角度。

enter image description here

EDIT 我已經改變了plot_hatches代碼以在逆時針方向方式旋轉(這是這個編輯之前的順時針方向)。這現在將產生與陣列[0, -45, 0, 45, 0]問題中給出的完全一致的圖像: enter image description here

+0

非常感謝。如果你不介意,我有幾個問題。所以這就產生了隨機角度的影線,我怎麼能用它指定的數組產生一個1X4的格子呢? [0,63,86,-11]?所以基本上我想能夠指定角度。再次感謝您的幫助! – user2739143

+0

在for循環中我調用'plot_hatches',它有兩個參數:第一個是要繪製的軸,第二個是角度。要使其成爲1x4,您需要更改'plt.subplots'中的行數和列數(這是創建軸的位置)。然後,只需運行for循環,而不是從列表中隨意給角度插入角度。我建議你把這個文件保存爲一個腳本,然後進行破解。讓我知道如果你卡住了。 – Greg

+0

格雷格,我已經改變了它,所以我可以指定我自己的角度陣列,但角度似乎並不正確。我編輯了原始問題向你展示。 – user2739143

相關問題