如何在Matplotlib表格中为特定单元格分配特定颜色?

18

在遵循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以及此示例仅向我展示如何应用具有预定义颜色的颜色映射,这些颜色取决于单元格中的值。
如何在Matplotlib生成的表格中为特定单元格分配特定颜色?
2个回答

31

在表格中着色单元格背景的最简单方法是使用 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()

输入图像描述

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

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

导致与上述输出相同的结果。


3
@ImportanceOfBeingErnest提供了一篇很好的答案。但是对于早期版本的Matplotlib,第二种方法如下:
the_table[(1, 0)].set_facecolor("#56b5fd")

会导致 TypeError: TypeError: 'Table' 对象没有属性 '__getitem__',可以通过使用以下语法来克服 TypeError:

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

另请参阅此示例。

(在Matplotlib 1.3.1上确认)

样本图


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接