关于程序员:创建华丽的数据展示表格使用Plottable库让DataFrame样式变得简单

4次阅读

共计 3338 个字符,预计需要花费 9 分钟才能阅读完成。

最近 github 上发现了一个库(plottable),能够用简略的形式就设置出花哨的 DataFrame 款式。

github 上的地址:https://github.com/znstrider/plottable

1. 装置

通过 pip 装置:

pip install plottable

2. 行的色彩

应用 plottable 的 API,调整背景和字体的色彩十分不便。

2.1. 奇偶行不同色彩

奇偶行设置不同的色彩,让表格看起来有层次感。

import numpy as np

from plottable import Table

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])
tbl = Table(df,
            odd_row_color="#f0f0f0",
            even_row_color="#e0f6ff"
           )

2.2. 背景和字体色彩

对于简单的显示要求,能够逐行设置背景色和字体的色彩。

import numpy as np

from plottable import Table

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])
tbl = Table(df)
tbl.rows[0].set_facecolor("red")
tbl.rows[0].set_fontcolor("white")

tbl.rows[1].set_facecolor("blue")
tbl.rows[1].set_fontcolor("white")

tbl.rows[2].set_facecolor("green")
tbl.rows[2].set_fontcolor("white")

tbl.rows[3].set_facecolor("gray")
tbl.rows[3].set_fontcolor("white")

tbl.rows[4].set_facecolor("purple")
tbl.rows[4].set_fontcolor("white")

上例中每一行的背景设置了不同的色彩,字体都设置为红色。

3. 值的显示

调整色彩,字体属于根本的设置,plottable 弱小之处在于可用图形化的形式来显示数据,
让咱们能够一眼看出数据的大小和差距。

比方,上面的示例用 ColumnDefinition 来应用 plottable 内置的数据显示方式。

import numpy as np

from matplotlib.colors import LinearSegmentedColormap

from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut

data = np.random.random((5, 5))
data = data.round(2)
df = pd.DataFrame(data, columns=["A", "B", "C", "D", "E"])

print(df) # 显示原始数据

cmap = LinearSegmentedColormap.from_list(name="bugw", colors=["#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"], N=256
)
tab = Table(
    df,
    textprops={"ha": "center"},
    column_definitions=[ColumnDefinition("index", textprops={"ha": "left"}),
        ColumnDefinition("A", plot_fn=percentile_bars, plot_kw={"is_pct": True}),
        ColumnDefinition("B", width=1.5, plot_fn=percentile_stars, plot_kw={"is_pct": True}
        ),
        ColumnDefinition(
            "C",
            plot_fn=progress_donut,
            plot_kw={"is_pct": True, "formatter": "{:.0%}"},
        ),
        ColumnDefinition(
            "D",
            width=1.25,
            plot_fn=bar,
            plot_kw={
                "cmap": cmap,
                "plot_bg_bar": True,
                "annotate": True,
                "height": 0.5,
                "lw": 0.5,
                "formatter": decimal_to_percent,
            },
        ),
    ],
)

原始数据显示:

plottable 强化之后显示:

4. 图文混合

最初,演示一个通过 plottable 在表格中插入图片的示例。
其中数据起源是 2023 王者光荣秋季赛各个战队的数据

次要为了演示表格中插入图片(图片是各个战队的 logo),所以只筛选了 4 个列来展现。

import pandas as pd
import numpy as np

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

from plottable import ColumnDefinition, Table
from plottable.formatters import decimal_to_percent
from plottable.plots import bar, percentile_bars, percentile_stars, progress_donut
from plottable.plots import circled_image

matplotlib.rcParams["font.sans-serif"] = ["Microsoft YaHei Mono"]
matplotlib.rcParams["axes.unicode_minus"] = False

df = pd.read_csv("d:/share/data.csv")
df = df.set_index("排名")
df["胜率"] = df["胜场"] / df["较量场次"]
df["logo"] = "d:/share/wzry-logos/" + df["战队"] + ".png"
df = df.drop(columns=["胜场", "较量场次", "场均 KDA"])

fig, ax = plt.subplots(figsize=(12, 12))

col_defs = [ColumnDefinition("排名", textprops={"ha": "left"}),
        ColumnDefinition(
            name="logo",
            title="",
            textprops={"ha": "center"},
            width=0.5,
            plot_fn=circled_image,
        ),
        ColumnDefinition("战队", textprops={"ha": "center"}),
        ColumnDefinition(
            "胜率",
            plot_fn=progress_donut,
            plot_kw={"is_pct": True, "formatter": "{:.0%}"},
        ),
    ]

tbl = Table(
    df,
    ax=ax,
    textprops={"ha": "center", "fontsize": 20},
    column_definitions=col_defs,
)

下面示例中用到的数据和 logo 图标分享在:
https://url11.ctfile.com/f/45455611-870642180-a094e4?p=6872 (拜访明码: 6872)

有趣味能够试试看下面的示例,或者持续深刻摸索 plottable 的弱小显示性能。

本文由 mdnice 多平台公布

正文完
 0