Create gorgeous data display tables: Use the Plottable library to make DataFrame styling simple

Recently I discovered a library ( plottable) on github that can set up fancy DataFramestyles in a simple way.

Address on github: https://github.com/znstrider/plottable

1. Installation

Install via pip:

pip install plottable

2. Row color

Using plottablethe API, it is very convenient to adjust the background and font color.

2.1. Different colors for odd and even rows

Set different colors for odd and even rows to make the table look layered.

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"
           )
image.png
image.png

2.2. Background and font color

For complex display requirements, the background color and font color can be set line by line.

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")

image.png
In the above example, the background of each row is set to a different color, and the font is set to white.

3. Display of values

Adjusting colors and fonts are basic settings. plottableThe power is that the data can be displayed graphically,
allowing us to see the size and gaps of the data at a glance.

For example, the following example ColumnDefinitionuses plottablethe built-in data display.

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,
            },
        ),
    ],
)

Raw data shows:
image.png

plottableAfter strengthening, it shows:
image.png

4. Mixing graphics and text

Finally, an plottableexample of inserting a picture into a table is shown.
The data source is the data of each team in the 2023 Honor of Kings Spring Split .

The main purpose is to insert pictures into the demonstration table (the pictures are the logos of each team), so only 4 columns are selected for display.

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,
)
image.png
image.png

The data and logo icon used in the above example are shared at:
https://url11.ctfile.com/f/45455611-870642180-a094e4?p=6872 (access password: 6872)

有兴趣可以试试看上面的示例,或者继续深入探索 plottable 的强大显示功能。

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/qq_37462361/article/details/132532262