如何为Matplotlib表中的特定单元格分配特定颜色? [英] How to assign specific colors to specific cells in a Matplotlib table?
问题描述
在pylab_examples之后,我在matplotlib中创建了一个简单的2x5单元格表。
代码:
#准备表
列=('A','B','C','D','E')
行= [ A, B]
cell_text = [[ 1, 1, 1, 1, 1],[ 2, 2, 2, 2, 2]]
#在轴
ax [4] .axis('tight')
ax [4]的底部添加一个表格。 axis('off')
the_table = ax [4] .table(cellText = cell_text,colLabels = columns,loc ='center')
现在,我想为 color =#56b5fd
的单元格A1和的单元格A2着色color =#1ac3f5
。所有其他单元格应保持白色。 Matplotlib的
或者,您可以将特定单元格的面色设置为
the_table [(1,0)]。set_facecolor(#56b5fd)
the_table [(2,0 )]。set_facecolor(#1ac3f5)
与以下结果相同以上。
Following the pylab_examples, I have created a simple 2x5 cells table in matplotlib.
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"
. 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.
How to assign specific colors to specific cells in a Matplotlib-generated table?
The easiest way to colorize the background of cells in a table is to use the cellColours
argument. 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
the_table[(1, 0)].set_facecolor("#56b5fd")
the_table[(2, 0)].set_facecolor("#1ac3f5")
Resulting in the same output as above.
这篇关于如何为Matplotlib表中的特定单元格分配特定颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!