Home > database >  How to annotate a gridded plot with values from a dict
How to annotate a gridded plot with values from a dict

Time:11-09

I have this Matplotlib grid and would like to write text in each of the grid cells. The text is provided by a dictionary. How would I do this?

Here's what I have so far:

fig, ax = plt.subplots()
plt.xlim(0, 3)
plt.ylim(3, 0)
plt.grid(True)
plt.xticks(np.arange(0, 4, 1.0))
plt.yticks(np.arange(0, 4, 1.0))

dictionary = {0: {'down': 58, 'right': 43, 'up': 9, 'left': 2},
              1: {'down': 23, 'right': 35, 'up': 1, 'left': 1},
              2: {'down': 4,  'right': 23, 'up': 0, 'left': 1},
              3: {'down': 21, 'right': 24, 'up': 1, 'left': 0},
              4: {'down': 24, 'right': 31, 'up': 2, 'left': 1},
              5: {'down': 6,  'right': 46, 'up': 1, 'left': 0},
              6: {'down': 25, 'right': 2, 'up': 1,  'left': 0 },
              7: {'down': 54, 'right': 4, 'up': 1,  'left': 1},
              8: {'down': 0,  'right': 0, 'up': 0,  'left': 0}
             }

The grid looks like this:

enter image description here

The grid cells are labeled 0 through 8, going vertically column wise (cell 2 is bottom left corner not top right corner). What I would like is to display the associated key-value pairs for each cell index, in the grid itself (like taking a pen and writing in the values in the appropriate cells, except programmatically).

Obviously it might get a little packed, and in that case I can make the grid itself bigger. But is there a way to display the text from the dictionary onto the grid, at each corresponding cell?

CodePudding user response:

  • Create a list of tuples for the (x, y) locations of the annotations using a list comprehension.
    • Down and Across: [(x 0.05, y 0.5) for x in range(3) for y in range(3)]
    • Across and Down: [(x 0.05, y 0.5) for y in range(3) for x in range(3)]
  • enter image description here

  • Related