我想畫一個網格,每個方格中都有箭頭,并在特定的單元格中著色。這就是我目前的成果。箭頭并沒有很好地居中,但我已經盡力了。
arrow_direction_per_cell = {(0, 0) 。'RIGHT', (0, 1): 'DOWN', (0, 2) 。'Up', (0, 3): 'LEFT', (0, 4): 'UP',
(1, 0) 。'RIGHT', (1, 1) 。'RIGHT',(1, 2): 'DOWN', (1, 3) 。'LEFT', (1, 4): 'LEFT', (2, 0) 。'RIGHT', (2, 1): 'RIGHT',
(2, 2) 。'DOWN',(2, 3): 'LEFT', (2, 4): 'UP', (3, 0) 。'LEFT', (3, 1): 'RIGHT', (3, 2) 。'UP', (3, 3) 。'LEFT', (3, 4): 'UP',
(4, 0) 。'LEFT', (4, 1): 'DOWN', (4, 2) 。'UP', (4, 3) 。'UP', (4, 4) 。'UP'}。
direction_map = {'UP':(0,1), 'DOWN': (0,-1),'RIGHT': (1,0),'LEFT':(-1,0) }
locations = arrow_direction_per_cell.keys()
fig, ax = plt.subplots()
plt.xlim(0, 5)
plt.ylim(5, 0)
plt.grid(True)
plt.xticks(np.range(0, 6, 1.0)
plt.yticks(np.range(0, 6, 1.0)
for location in locations:
arrow_direction = arrow_direction_per_cell[location] 。
x_pos,y_pos = (location[0] .5),(location[1] .5)
x_direct,y_direct = direction_map[arrow_direction] (箭頭方向)。
ax.quiver(x_pos, y_pos, x_direct, y_direct, scale=30)
cells_to_be_orange = [(0,2), (2, 4),(3,4) ]
cells_to_be_blue = [(3,2)]
ax.quiver(x_pos, y_pos, x_direct, y_direct)
plt.show()
我怎樣才能把'cell_to_be_orange'中的位置染成橙色,把'cell_to_be_blue'染成藍色,以及怎樣才能使箭頭看起來更居中?
非常感謝您,祝您有一個美好的一天。
uj5u.com熱心網友回復:
你只需添加一個函式cell_color并在ax.quiver()中呼叫它。
函式arrow_position試圖使箭頭居中,但你應該檢查一下是否有更好的解決方案。
#!/usr/bin/env python3。
import matplotlib.pyplot as plt
import numpy as np
arrow_direction_per_cell = {
(0, 0) 。'RIGHT', (0, 1) 。'DOWN' , (0, 2) 。'UP' , (0, 3) 。'LEFT', (0, 4): 'UP',
(1, 0) 。'RIGHT', (1, 1) 。'RIGHT', (1, 2) 。'DOWN', (1, 3) 。'LEFT', (1, 4): 'LEFT',
(2, 0) 。'RIGHT', (2, 1) 。'RIGHT', (2, 2) 。'DOWN', (2, 3) 。'LEFT', (2, 4): 'UP',
(3, 0) 。'LEFT', (3, 1): 'RIGHT', (3, 2) 。'UP' , (3, 3) 。'LEFT', (3, 4): 'UP',
(4, 0) 。'LEFT', (4, 1): 'DOWN' , (4, 2) 。'UP' , (4, 3) 。'UP' , (4, 4) 。'UP''UP' : ( 0, 1) 。
'DOWN' : ( 0,-1) 。
'RIGHT': ( 1, 0) 。
'LEFT' : ( -1, 0)
}
def arrow_color(location)。
cells_to_be_blue = [(3,2)]
cells_to_be_orange = [(0,2), (2, 4),(3,4) ]
if location in cells_to_be_orange:
回傳 "orange"。
elif location in cells_to_be_blue:
return "blue"
return "black"
def arrow_position(location, arrow_direction)。
if arrow_direction == 'UP':
修正 = (.5, .6)
elif arrow_direction == 'DOWN':
修正 = (.5, .4)
elif arrow_direction == 'RIGHT':
更正 = (.4, .5)
elif arrow_direction == 'LEFT':
更正 = (.6, .5)
return (location[0] correction[0] 。
location[1] correction[1])
fig, ax = plt.subplots()
plt.xlim(0, 5)
plt.ylim(5, 0)
plt.grid(True)
plt.xticks(np.range(0, 6, 1.0)
plt.yticks(np.range(0, 6, 1.0)
locations = arrow_direction_per_cell.keys()
for location in locations:
arrow_direction = arrow_direction_per_cell[location] 。
x_pos, y_pos = arrow_position(location, arrow_direction)
x_direct, y_direct = direction_map[ arrow_direction]
ax.quiver(
x_pos, y_pos,
x_direct, y_direct,
color=arrow_color(location),
scale=30)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312408.html
標籤:
上一篇:如何在使用subplots_adjust時保持嵌套軸的位置
下一篇:如何為子圖的行和列添加標簽?


