如何更改表格中单元格的文本颜色?

时间:2019-11-12 11:38:22

标签: python matplotlib

我正在绘制一张表格,其中某个单元格内的文本应根据其值更改其颜色。 Herehere我发现方法table._cells[(i,j)]._text.set_color('color')似乎很有帮助,但不幸的是,在我的代码中使用该方法会引发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()

谁能告诉我我犯了什么错误?

2 个答案:

答案 0 :(得分:1)

行标签以负数索引,所以您可能想要

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') 

此外,您可以使用table[2, 0]代替table._cells[2, 0]。另外,单元格类具有get_text方法,该方法可以避免访问“专用”属性:table[(2, 0)].get_text().set_color('#FF0000')

答案 1 :(得分:1)

当您查看table._cells时,您会发现键[(2,1)]不存在:

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>}

当我将[(2,1)]替换为[(1,0)]时,它对我有用