按照 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 着色和单元格 A2 带有 color = "#1ac3f5"
.所有其他单元格应保持白色。 Matplotlib 的 table_demo.py以及 this示例仅向我展示了如何应用具有取决于单元格中值的预定义颜色的颜色图。如何为 Matplotlib 生成的表格中的特定单元格分配特定颜色?
最佳答案
为表格中的单元格背景着色的最简单方法是使用 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()
或者,您可以将特定单元格的 facecolor 设置为
the_table[(1, 0)].set_facecolor("#56b5fd")
the_table[(2, 0)].set_facecolor("#1ac3f5")
导致与上面相同的输出。
关于python - 如何为 Matplotlib 表中的特定单元格分配特定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46663911/