2017-05-05 68 views
1

我有一個3x4的狀態矩陣和一個4x12的方向矩陣。如何控制plt.quiver?

states = 3x4 matrix 
directions = 4x12 matrix 

方向矩陣在每列上有許多動作:向上,向右,向下,向左。例如,如果我們在state[0,0],我們想知道下一步去哪裏,我們檢查方向矩陣directions[:,0],並根據所行具有最高的價值,我們是這樣的:

-for row 0 we pick up 
-for row 1 we pick right 
-for row 2 we pick down 
-for row 3 we pick left 

現在我正在努力使用python的plt.quiver函數在首選方向上顯示箭頭,但我找不到任何有用的資源。我發現和理解的唯一事情是這樣的:

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.quiver((0,0), (0,0), (1,0), (1,3), units = 'xy', scale = 1) 
plt.axis('equal') 

plt.xticks(range(-5,6)) 
plt.yticks(range(-5,6)) 
plt.grid() 
plt.show() 

基本上示出了從(0,0)至(1,1)從(0,0)至(1,3)和箭頭另一個但我想不出通過更新這個來實現我想要的方式。 有沒有人有任何建議?

我想要做的是這樣的https://matplotlib.org/2.0.0/examples/pylab_examples/quiver_demo.html("pivot='mid'; every third arrow; units='inches'")例子。

回答

1

我想下面的例子會做你需要的。

import numpy as np; np.random.seed(1) 
import matplotlib.pyplot as plt 

states = np.random.randint(0,2,size=(3,4)) 
directions = np.round(np.random.rand(4,12), 2) 

x,y = np.meshgrid(np.arange(states.shape[1]), np.arange(states.shape[0])) 
dirstates = np.argmax(directions, axis=0).reshape(3,4) 

dirx = np.sin(dirstates*np.pi/2.) 
diry = np.cos(dirstates*np.pi/2.) 

fig, ax = plt.subplots() 
ax.quiver(x,y,dirx,diry) 
ax.margins(0.2) 
plt.show() 

enter image description here

+0

哈哈,好一個。我最終做的是'X = np.array([0,1,2,3,0,1,2,3,0,1,2,3])' 'Y = np.array([2 ,2,2,2,1,1,1,1,0,0,0,0])'對於方向,我只需要argmax,然後對於U,VI只會給出方向爲0,1或1,1。您的解決方案非常優雅。我的空間是雙倍的。 – iDaniel19