如何为Matplotlib表中的特定单元格指定特定颜色?

时间:2017-10-10 10:01:07

标签: python matplotlib colors

在pylab_examples之后,我在matplotlib中创建了一个简单的2x5单元格表。

代码:

# Prepare table
columns = ('A', 'B', 'C', 'D', 'E')
rows = ["A", "B"]
cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]]
# Add a table at the bottom of the axes
ax[4].axis('tight')
ax[4].axis('off')
the_table = ax[4].table(cellText=cell_text,colLabels=columns,loc='center')

现在,我想用color = "#56b5fd"为单元格A1着色,用color = "#1ac3f5"对单元格A2进行着色。所有其他细胞应保持白色。 Matplotlib的table_demo.py以及this示例仅向我展示如何应用具有取决于单元格中的值的预定义颜色的颜色贴图。

如何为Matplotlib生成的表格中的特定单元格指定特定颜色?

2 个答案:

答案 0 :(得分:7)

对表格中单元格背景进行着色的最简单方法是使用cellColours参数。您可以提供列表列表或与数据具有相同形状的阵列。

import matplotlib.pyplot as plt
# Prepare table
columns = ('A', 'B', 'C', 'D', 'E')
rows = ["A", "B"]
cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]]
# Add a table at the bottom of the axes
colors = [["#56b5fd","w","w","w","w"],[ "#1ac3f5","w","w","w","w"]]

fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText=cell_text,cellColours=colors,
                     colLabels=columns,loc='center')

plt.show()

enter image description here

或者,您可以将特定单元格的面部颜色设置为

the_table._cells[(1, 0)].set_facecolor("#56b5fd")
the_table._cells[(2, 0)].set_facecolor("#1ac3f5")

产生与上述相同的输出。

答案 1 :(得分:0)

@ImportanceOfBeingErnest提供了一个很好的答案。但是,对于早期版本的Matplotlib,第二种方法是:

the_table[(1, 0)].set_facecolor("#56b5fd")

将导致TypeError:TypeError: 'Table' object has no attribute '__getitem__'可以通过使用以下语法来克服TypeError:

the_table.get_celld()[(1,0)].set_facecolor("#56b5fd")
the_table.get_celld()[(2,0)].set_facecolor("#1ac3f5")

See also this example.

(在Matplotlib 1.3.1上确认)

Sample plot