首页 > 解决方案 > 如何为 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,则单元格为红色;否则它们是绿色的。这应该是这样的: 在此处输入图像描述

标签: pythonpandasmatplotlib

解决方案


生成列表列表并将其提供给 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()

推荐阅读