简体   繁体   English

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

[英]How to assign specific colors to specific cells in a Matplotlib table?

Following the pylab_examples, I have created a simple 2x5 cells table in matplotlib.按照 pylab_examples,我在 matplotlib 中创建了一个简单的 2x5 单元格表。

Code:代码:

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

Now, I want to color cell A1 with color = "#56b5fd" and cell A2 with color = "#1ac3f5" .现在,我想使用color = "#56b5fd"为单元格 A1 color = "#56b5fd"并使用color = "#56b5fd"单元格 A2 color = "#1ac3f5" All other cells should remain white.所有其他单元格应保持白色。 Matplotlib's table_demo.py as well as this example only show me how to apply a color map with pre-defined colors that depend on the values in the cell. Matplotlib 的table_demo.py以及示例仅向我展示了如何应用具有取决于单元格中值的预定义颜色的颜色图。

How to assign specific colors to specific cells in a Matplotlib-generated table?如何为 Matplotlib 生成的表格中的特定单元格分配特定颜色?

The easiest way to colorize the background of cells in a table is to use the cellColours argument.为表格中的单元格背景着色的最简单方法是使用cellColours参数。 You may supply a list of lists or an array with the same shape as the data.您可以提供与数据具有相同形状的列表列表或数组。

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

在此处输入图片说明

Alternatively, you can set the facecolor of a specific cell as或者,您可以将特定单元格的 facecolor 设置为

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

Resulting in the same output as above.导致与上面相同的输出。

@ImportanceOfBeingErnest provided an excellent answer. @ImportanceOfBeingErnest 提供了一个很好的答案。 However, for earlier versions of Matplotlib, the second approach:但是,对于早期版本的 Matplotlib,第二种方法:

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

will result in a TypeError: TypeError: 'Table' object has no attribute '__getitem__' The TypeError can be overcome by using the following syntax instead:将导致 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.另请参见此示例。

(Confirmed on Matplotlib 1.3.1) (在 Matplotlib 1.3.1 上确认)

样地

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM