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

标签 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 着色和单元格 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()

enter image description here

或者,您可以将特定单元格的 facecolor 设置为
the_table[(1, 0)].set_facecolor("#56b5fd")
the_table[(2, 0)].set_facecolor("#1ac3f5")

导致与上面相同的输出。

关于python - 如何为 Matplotlib 表中的特定单元格分配特定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46663911/

相关文章:

python - 在 python 中的单个图上绘制具有几何点和线的 shapefile

macos - 更改插入符号的颜色 SwiftUI TextField MacOS

image - 在Matlab中将彩色像素添加到灰度图像

python - 是什么导致 Cassandra CQL 出现 "no viable alternative at input ' None'"错误

python - 当类型为 'super()' 时 'object' 的行为?

Python 使用 Seaborn Relplot 绘制带有列表单元格的数据框

android - 调整 Android 设备的色彩空间

python - Project Euler 在 python 中获得最小倍数

Python unicode 相等比较在终端中失败,但在 Spyder 编辑器下工作

python - 在 Python Matplotlib 中将图形保存为 eps 时出错