【问题标题】:How to change cell's text color in table?如何更改表格中单元格的文本颜色?
【发布时间】:2019-11-12 11:38:22
【问题描述】:

我正在绘制一个表格,其中某个单元格内的文本应根据其值更改其颜色。 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()

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

【问题讨论】:

    标签: python matplotlib


    【解决方案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)] 时,它对我有用

    【讨论】:

      【解决方案2】:

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

      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]。另外,cell 类有一个get_text 方法,可以避免访问“private”属性:table[(2, 0)].get_text().set_color('#FF0000')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-11
        • 1970-01-01
        • 2013-03-23
        • 2015-01-24
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        • 2019-11-16
        相关资源
        最近更新 更多