python - 如何为 matplotlib 表值创建条件着色?
问题描述
如何向此表添加条件着色?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A':[16, 15, 14, 16],
'B': [3, -2, 5, 0],
'C': [200000, 3, 6, 800000],
'D': [51, -6, 3, 2]})
fig, ax = plt.subplots(figsize=(10,5))
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText = df.values, colLabels = df.columns, loc='center')
plt.show()
如何将条件着色添加到 A 列和 D 列值大于或等于 15 的表中,单元格为红色;否则它们是绿色的。如果 B 列和 C 列的值大于或等于 5,则单元格为红色;否则它们是绿色的。这应该是这样的:
解决方案
生成列表列表并将其提供给 cellColours。确保列表列表包含与数据框中的行一样多的列表,并且列表列表中的每个列表包含与数据框中的列一样多的字符串。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A':[16, 15, 14, 16],
'B': [3, -2, 5, 0],
'C': [200000, 3, 6, 800000],
'D': [51, -6, 3, 2]})
colors = []
for _, row in df.iterrows():
colors_in_column = ["g", "g", "g", "g"]
if row["A"]>=15:
colors_in_column[0] = "r"
if row["B"]>=5:
colors_in_column[1] = "r"
if row["C"]>5:
colors_in_column[2] = "r"
if row["D"]>=15:
colors_in_column[3] = "r"
colors.append(colors_in_column)
fig, ax = plt.subplots(figsize=(10,5))
ax.axis('tight')
ax.axis('off')
the_table = ax.table(cellText = df.values, colLabels = df.columns, loc='center', cellColours=colors)
plt.show()
推荐阅读
- sql - 我需要创建一个列,其中相同值保留在表中的次数。SQL 服务器
- flutter - Dart 中的单行构造函数赋值
- python - 已安装 PYSMB 丢失
- javascript - 无法将电话号码显示为 E. 164 的格式。使用 intl-tel-input
- asp.net-mvc - 如何访问在某个控制器中创建的 Viewbag 中的项目并在另一个控制器中使用它?
- python - 这些 while 语句的顺序如何工作?
- node.js - 在开玩笑测试中关闭猫鼬连接会导致匹配器错误
- java - 如何在 Spring 应用程序中在运行时更改依赖 jar 而无需重新启动应用程序本身?
- c++ - 在 Linux Lite 上的文本编辑器、Visual Studio 代码 (gcc) 中,如何配置编译器以使输出选项卡改为输出窗口?
- java - 如何为从服务器填充数据的活动设计预加载器?