Home > database >  plot a grid with arrows on it
plot a grid with arrows on it

Time:06-25

I have a matrix like below:

enter image description here

First for each cell I want to find maximum neighbor. Then in a grid, plot an arrow in every cell such that the direction of arrow is to the max neighbor.

Each cell has at most 4 neighbors in directions left, right, up and down.

the output is something like this:

enter image description here

I have no idea how plot this in python with matplotlib or any other library. here's a short block of code:

import numpy as np
import matplotlib.pyplot as plt

matrix = [[22, 24.4, 22, 19.4, 17.5],
          [19.8, 22, 19.8, 17.8, 16],
          [17.8, 19.8, 17.8, 16, 14.4],
          [16, 17.8, 16, 14.4, 13],
          [14.4, 16, 14.4, 13, 11.7]]

#.... after some processes
#L, R, D, U means left, right, up and down
arrows = [['R', 'D', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L']]
#plot arrows!!

How Plot arrows in a grid? If arrows[i][j] == 'R' then plot an arrow pointed right in position [i][j] on grid, and so on.

CodePudding user response:

Try

matplotlib.pyplot.arrow(x, y, dx, dy, **kwargs)

Sample code:

arrows = {"R":(1,0), "L":(-1,0),"U":(0,1),"D":(0,-1)}
scale = 0.25

ar =     [['R', 'D', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L'],
          ['U', 'U', 'L', 'L', 'L']]

fig, ax = plt.subplots(figsize=(6, 6))
for r, row in enumerate(ar):
    for c, cell in enumerate(row):
        plt.arrow(c, 5-r, scale*arrows[cell][0], scale*arrows[cell][1], head_width=0.1)

Output: enter image description here

  • Related