1

I am plotting a table where text inside a certain cell should change its color depending on its value. Here and here I found the method table._cells[(i,j)]._text.set_color('color') which seems very helpfull but unfortunately using it in my code raises the KeyError: (2, 1).

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

val1 = 0.3
val2 = -0.7
solution = val1 - val2

row_labels = ['sum1', 'sum2',
                  'sol']
if val2 >= 0:
    table_vals = [[val1], ['-   '+str(val2)], ['=   '+str(solution)]]
else:
    table_vals = [[val1], ['-   ('+str(val2)+')'], ['=   '+str(solution)]]

table = ax.table(cellText=table_vals, rowLabels=row_labels,
                 colWidths=[0.1]*2, bbox = [0.3, 0.1, 0.3, 0.3])

for key, cell in table.get_celld().items():
    cell.set_edgecolor('#FFFFFF')
    cell.set_facecolor('#636363')
    cell._text.set_color('#FFFFFF')

if -0.25 < solution < 0.25:
    table._cells[(2, 1)]._text.set_color('#008000')  # raises KeyError
elif -0.5 < solution <= -0.25 or 0.25 <= solution < 0.5:
    table._cells[(2, 1)]._text.set_color('#FFFF00')  # raises KeyError
else:
    table._cells[(2, 1)]._text.set_color('#FF0000')  # raises KeyError

plt.show()

Can anyone tell me what mistakes I made?

Philipp
  • 323
  • 4
  • 19

2 Answers2

3

When you look at table._cells you can see that the key [(2,1)] doesn't exists:

In [9]: table._cells
Out[9]: 
{(0, 0): <matplotlib.table.CustomCell at 0x2e18197a0f0>,
 (1, 0): <matplotlib.table.CustomCell at 0x2e18197a2b0>,
 (2, 0): <matplotlib.table.CustomCell at 0x2e18197a438>,
 (0, -1): <matplotlib.table.CustomCell at 0x2e18197a5c0>,
 (1, -1): <matplotlib.table.CustomCell at 0x2e18197a748>,
 (2, -1): <matplotlib.table.CustomCell at 0x2e18197a8d0>}

It works for me when I replace [(2,1)] with [(1,0)]

Zephyrus
  • 366
  • 1
  • 10
1

The row labels are indexed with negative numbers, so you probably want

if -0.25 < solution < 0.25:
    table._cells[(2, 0)]._text.set_color('#008000')  
elif -0.5 < solution <= -0.25 or 0.25 <= solution < 0.5:
    table._cells[(2, 0)]._text.set_color('#FFFF00')  else:
    table._cells[(2, 0)]._text.set_color('#FF0000') 

Also, you can use table[2, 0] instead of table._cells[2, 0]. In addition, the cell class has a get_text method, which allows to avoid accessing the "private" attribute: table[(2, 0)].get_text().set_color('#FF0000').

mcsoini
  • 6,280
  • 2
  • 15
  • 38