服务粉丝

我们一直在努力
当前位置:首页 > 财经 >

Python搞定表格可视化!

日期: 来源:简说Python收集编辑:pythonic生物人

分享一个Python工具plottable,轻松制作高度个性化的表格,底层为Matplotlib。

例如这样的,或者这样的,第一张图详细代码:

# 导入相关包
from pathlib import Path

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap

from plottable import ColumnDefinition, Table
from plottable.cmap import normed_cmap
from plottable.formatters import decimal_to_percent
from plottable.plots import circled_image

plt.rcParams["font.family"] = ["DejaVu Sans"]
plt.rcParams["savefig.bbox"] = "tight"

# demo数据准备
cols = [
    "team",
    "points",
    "group",
    "spi",
    "global_o",
    "global_d",
    "group_1",
    "group_2",
    "group_3",
    "make_round_of_16",
    "make_quarters",
    "make_semis",
    "make_final",
    "win_league",
]

df = pd.read_csv(
    "data/wwc_forecasts.csv",
    usecols=cols,
)

colnames = [
    "Team",
    "Points",
    "Group",
    "SPI",
    "OFF",
    "DEF",
    "1st Place",
    "2nd Place",
    "3rd Place",
    "Make Rd Of 16",
    "Make Quarters",
    "Make Semis",
    "Make Finals",
    "Win World Cup",
]

col_to_name = dict(zip(cols, colnames))

flag_paths = list(Path("country_flags").glob("*.png"))
country_to_flagpath = {p.stem: p for p in flag_paths}

df[["spi", "global_o", "global_d"]] = df[["spi", "global_o",
                                          "global_d"]].round(1)

df = df.rename(col_to_name, axis=1)
df = df.drop("Points", axis=1)
df.insert(0, "Flag", df["Team"].apply(lambda x: country_to_flagpath.get(x)))

df = df.set_index("Team")

# colormap准备
cmap = LinearSegmentedColormap.from_list(
    name="bugw",
    colors=["#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"],
    N=256)

team_rating_cols = ["SPI", "OFF", "DEF"]
group_stage_cols = ["1st Place", "2nd Place", "3rd Place"]
knockout_stage_cols = list(df.columns[-5:])

# table列个性化list,例如列名、列宽、字体、磅值等等
col_defs = ([
    ColumnDefinition(
        name="Flag",
        title="Region",
        textprops={"ha": "center"},
        width=0.5,
        plot_fn=circled_image,
    ),
    ColumnDefinition(
        name="Team",
        textprops={
            "ha": "left",
            "weight": "bold"
        },
        width=1.5,
    ),
    ColumnDefinition(
        name="Group",
        textprops={"ha": "center"},
        width=0.75,
    ),
    ColumnDefinition(
        name="SPI",
        group="Team Rating",
        textprops={"ha": "center"},
        width=0.75,
    ),
    ColumnDefinition(
        name="OFF",
        width=0.75,
        textprops={
            "ha": "center",
            "bbox": {
                "boxstyle": "circle",
                "pad": 0.35
            },
        },
        cmap=normed_cmap(df["OFF"], cmap=matplotlib.cm.Blues, num_stds=2.5),
        group="Team Rating",
    ),
    ColumnDefinition(
        name="DEF",
        width=0.75,
        textprops={
            "ha": "center",
            "bbox": {
                "boxstyle": "circle",
                "pad": 0.35
            },
        },
        cmap=normed_cmap(df["DEF"], cmap=matplotlib.cm.Greens, num_stds=2.5),
        group="Team Rating",
    ),
] + [
    ColumnDefinition(
        name=group_stage_cols[0],
        title=group_stage_cols[0].replace(" ", "\n", 1),
        formatter=decimal_to_percent,
        group="Group Stage Chances",
        border="left",
    )
] + [
    ColumnDefinition(
        name=col,
        title=col.replace(" ", "\n", 1),
        formatter=decimal_to_percent,
        group="Group Stage Chances",
    ) for col in group_stage_cols[1:]
] + [
    ColumnDefinition(
        name=knockout_stage_cols[0],
        title=knockout_stage_cols[0].replace(" ", "\n", 1),
        formatter=decimal_to_percent,
        cmap=cmap,
        group="Knockout Stage Chances",
        border="left",
    )
] + [
    ColumnDefinition(
        name=col,
        title=col.replace(" ", "\n", 1),
        formatter=decimal_to_percent,
        cmap=cmap,
        group="Knockout Stage Chances",
    ) for col in knockout_stage_cols[1:]
])

# plottable的Table方法制作表格

fig, ax = plt.subplots(figsize=(20, 22))
table = Table(
    df,
    column_definitions=col_defs,
    row_dividers=True,
    footer_divider=True,
    ax=ax,
    textprops={
        "fontsize": 14
    },
    row_divider_kw={
        "linewidth": 1,
        "linestyle": (0, (1, 5))
    },
    col_label_divider_kw={
        "linewidth": 1,
        "linestyle": "-"
    },
    column_border_kw={
        "linewidth": 1,
        "linestyle": "-"
    },
).autoset_fontcolors(colnames=["OFF", "DEF"])

留言说说你常用的数据可视化技巧~互相学习。


加我微信,了解更多 Python、Go 知识,了解更多优惠活动。


扫码即可加我微信


    相关阅读

    • 连中两篇WWW顶会!

    • Datawhale干货 作者:鸣也,中国科学院大学,Datawhale成员转载自公众号:Datawhale很幸运能在WWW23中稿两篇论文,作为22年中旬才开始做深度学习方面的科研新手来说,给即将入门科研的
    • Python的那些"地图"神器!

    • 老表荐书图书介绍:《Python金融量化分析学习教程》本书是有关Python在金融量化分析领域应用的一本从入门到精通类图书。全书分4篇共10章。第1篇(第1~3章)简单介绍了Python的基
    • 对比Excel系列的又一本新书发布!

    • 数据相关从业者应该都听过《对比Excel系列》图书,这个系列累计销量已超20w册,预计影响了10w+数据人。时隔一年,对比Excel系列的又一本新书发布,就是下面这本《对比Excel,轻松学习
    • 《HelloGitHub》第 82 期

    • 兴趣是最好的老师,HelloGitHub 让你对编程感兴趣!简介HelloGitHub 分享 GitHub 上有趣、入门级的开源项目。https://github.com/521xueweihan/HelloGitHub这里有实战项目、入
    • 2023 年该学点什么技术?「GitHub 热点速览 v.23.03」

    • 作者:HelloGitHub-小鱼干春节期间,小鱼干读了一篇万字回顾数据库行业的文章,在文字缝隙里我看见了两个词:AI+ 和数据两个词(当然数据是废话,毕竟是一个数据库的回顾文)。在 GitHub
    • 让人眼前一亮的应用「GitHub 热点速览」

    • 作者:HelloGitHub-小鱼干大开眼界的一期 GitHub 热门项目,类似 Django 存在的 pynecone,搞定 Windows、Office 激活的 Microsoft-Activation-Scripts,都让我的收藏夹蠢蠢欲动。
    • 如何让程序更健壮「GitHub 热点速览」

    • 作者:HelloGitHub-小鱼干对于 ML 模型训练而言,好的数据集能让结果更健壮,cleanlab 是一个降低数据噪音,及时帮你修正数据集错误的工具。好的工具能让你的结果更完美。同样的,Red

    热门文章

    • “复活”半年后 京东拍拍二手杀入公益事业

    • 京东拍拍二手“复活”半年后,杀入公益事业,试图让企业捐的赠品、家庭闲置品变成实实在在的“爱心”。 把“闲置品”变爱心 6月12日,“益心一益·守护梦想每一步”2018年四

    最新文章

    • Python搞定表格可视化!

    • 分享一个Python工具plottable,轻松制作高度个性化的表格,底层为Matplotlib。例如这样的,或者这样的,第一张图详细代码:# 导入相关包from pathlib import Pathimport matplotlibim
    • 连中两篇WWW顶会!

    • Datawhale干货 作者:鸣也,中国科学院大学,Datawhale成员转载自公众号:Datawhale很幸运能在WWW23中稿两篇论文,作为22年中旬才开始做深度学习方面的科研新手来说,给即将入门科研的
    • Python的那些"地图"神器!

    • 老表荐书图书介绍:《Python金融量化分析学习教程》本书是有关Python在金融量化分析领域应用的一本从入门到精通类图书。全书分4篇共10章。第1篇(第1~3章)简单介绍了Python的基
    • 豆瓣9.3,这部神作终于升级了!

    • 关注我们丨文末赠书扫下方二维码加我微信,2.10 将在朋友圈送几本给需要的读者朋友。扫码即可加我微信不久前,自称“业余up主”的AI大神李沐开源了一个剪辑神器 ,再圈一波技术粉
    • 对比Excel系列的又一本新书发布!

    • 数据相关从业者应该都听过《对比Excel系列》图书,这个系列累计销量已超20w册,预计影响了10w+数据人。时隔一年,对比Excel系列的又一本新书发布,就是下面这本《对比Excel,轻松学习
    • 《HelloGitHub》第 82 期

    • 兴趣是最好的老师,HelloGitHub 让你对编程感兴趣!简介HelloGitHub 分享 GitHub 上有趣、入门级的开源项目。https://github.com/521xueweihan/HelloGitHub这里有实战项目、入