有没有办法以交互式方式以表格格式可视化 pandas 数据框中的分类数据?

问题描述 投票:0回答:1

目标是创建一个名称从 1 到 20 的表,颜色编码为绿色表示早餐和午餐,黄色表示其中之一,红色表示该人没有吃任何饭菜。在 tableau 中很容易做到,但是有没有办法在 python 中做到?

以下是预期的

python pandas plotly
1个回答
0
投票

我希望这有帮助:

import pandas as pd
import matplotlib.pyplot as plt
import math

yellow = '#F4E04D'
red = '#D63230'
green = '#3A7D44'
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Beth'],
    'Breakfast': [True, False, False, True],
    'Lunch': [True, False, True, False]
}


df = pd.DataFrame(data)


def save_dataframe_as_png(df, filename):
    #compute colors
    names = []
    colors = []
    for _ , row in df.iterrows():
        if row['Breakfast'] and row['Lunch']:
            color = green
        elif row['Breakfast'] or row['Lunch']:
            color = yellow
        else:
            color = red
        names.append(row['Name'])
        colors.append(color)

    #compute table layout
    num_cols = min(math.ceil(math.sqrt(len(names))), 5)
    num_rows = math.ceil(len(names)/num_cols)
    num_empty_cells = max(0, num_cols*num_rows - len(colors))

    for _ in range(num_empty_cells):
        names.append('')
    names = [names[i:i+num_cols] for i in range(0, len(names), num_cols)]

    _ , ax = plt.subplots()

    #create table
    table = ax.table(cellText=names, loc='center', cellLoc='center')
    table.auto_set_font_size(False)
    table.set_fontsize(10)
    ax.axis('off')

    default_color = '#FFFFFF'
    
    #set background color
    for i in range(num_cols):
        for j in range(num_rows):
            if i * num_cols + j < len(colors):
                cell = table.get_celld()[i, j]
                cell.set_facecolor(colors[i * num_cols + j])
            else:
                cell = table.get_celld()[i, j]
                cell.set_facecolor(default_color)

    plt.savefig(filename)


save_dataframe_as_png(df, 'table.png')
© www.soinside.com 2019 - 2024. All rights reserved.