1

I have a dictionary of tuples of two non-negative integers (a,b), with a and b both at most 20. The dictionary maps each tuple to a float value between zero and one. I would like to create a two-dimensional grid where the unit square in the i-th column and the j-th row (corresponding to the tuple (i,j)) is colored with a grayscale value between white and black and proportional to its float value.

To clarify, my dictionary looks something like:

dict={(0, 0) : 0.04679,
      (0, 2) : 0.10936,
      (0, 4) : 0.17872000000000005,
      (2, 4) : 0.15046000000000004,
      (4, 4) : 0.026240000000000003,
      (1, 1) : 0.02055,
      (1, 2) : 0.10275
      ...
      }

I am unsure how to go about plotting this. Any help would be appreciated!

1 Answer 1

2

I'm sure there is a cleaner way to do this but this works -

import matplotlib.pyplot as plt
import numpy as np

d={(0, 0) : 0.04679,
   (0, 2) : 0.10936,
   (0, 4) : 0.17872000000000005,
   (2, 4) : 0.15046000000000004,
   (4, 4) : 0.026240000000000003,
   (1, 1) : 0.02055,
   (1, 2) : 0.10275
   (3, 3) : 0.84,
   (3, 2) : 0.62
}

x = []
y = []
v = []
for e in d.items():
    x.append(e[0][0])
    y.append(e[0][1])
    v.append(e[1])
m = np.zeros((max(x)+1, max(y)+1))
for ii in range(len(v)):
    m[x[ii]][y[ii]] = v[ii]
plt.matshow(m, cmap=plt.get_cmap('gray'), vmin=0.0, vmax=1.0)
plt.show()

The idea here is to parse the dictionary into a 2D numpy array which can then be directly plotted by plt.matshow(). If you want the missing values to be populated by ones instead of zeros you can use m = np.ones() instead of np.zeros(). If you don't want the minimum and maximum fixed to 0.0 and 1.0 respectively you can simply omit vmin=0.0 and vmax=1.0 in the call to matshow().

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.