【发布时间】:2019-11-12 11:38:22
【问题描述】:
我正在绘制一个表格,其中某个单元格内的文本应根据其值更改其颜色。 Here 和 here 我发现 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()
谁能告诉我我犯了什么错误?
【问题讨论】:
标签: python matplotlib