Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing only one key in a nested list of dictionaries and plotting it with matplotlib

I have a nested list of dictionaries, created like this:

N = 30
grid = []
for row in range(N):
   rows = []
   for column in range(N):
      each_cell = {"check": 0, "type": -1}
      rows.append(each_cell)
   grid.append(rows)

Type is the one that I want to plot, a value of -1 means nothing in the cell, and 0,1,2,3 are different types (not gradient), which I want to be represented by different colours.

I am putting a random number of types into the grid like this:

import numpy.random as rnd
import matplotlib.pyplot as plt

for i in range (rnd.randint(0, N*N)):
   x = rnd.randint(0, N)
   y = rnd.randint(0, N)
   grid[x][y]['check'] = 1
   if grid[x][y]['check'] == 1:
      grid[x][y]['type'] = rnd.randint(0,4)

I am attempting to plot it using this:

plt.imshow(grid['type'], interpolation = 'nearest', cmap = 'gist_ncar_r')
plt.show()

But obviously the grid['type'] isn't picking out only the types like I want it to, anybody know how to fix this?

like image 892
User41880 Avatar asked Nov 19 '25 18:11

User41880


1 Answers

Since imshow requires an 'array-like', you can change the structure of your data to make it easier to work with. Instead of using an array of dicts, use a dict of arrays.

import numpy.random as rnd
import matplotlib.pyplot as plt

N = 30
grid = {'check': [], 'type': []}

for row in range(N):
    check_rows = []
    type_rows = []
    for column in range(N):
        check_rows.append(0)
        type_rows.append(1)
    grid['check'].append(check_rows)
    grid['type'].append(type_rows)

for i in range (rnd.randint(0, N*N)):
    x = rnd.randint(0, N)
    y = rnd.randint(0, N)
    grid['check'][x][y] = 1
    if grid['check'][x][y] == 1:
        grid['type'][x][y] = rnd.randint(0,4)

plt.imshow(grid['type'], interpolation = 'nearest', cmap = 'gist_ncar_r')
plt.show()
like image 91
Mike Covington Avatar answered Nov 22 '25 08:11

Mike Covington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!