利用表格探索宜居城市

利用表格探索宜居城市

python 复制代码
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 PIL import Image

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

数据探索

以下数据如果有需要的同学可关注公众号HsuHeinrich,回复【数据可视化】自动获取~

python 复制代码
df = pd.read_csv(
    "https://raw.githubusercontent.com/fortune-uwha/Global-liveability-Index-2023/main/Data/cities.csv"
)

df.head()

旗帜图片可以关注公众号HsuHeinrich,回复【可视化素材】自动获取~

注:在country文件夹中

python 复制代码
# 数据预处理

# 重置字段顺序
columns_titles = ["City", "Location", "Rank", "Index", "Stability","Healthcare", "Education", "Culture_Environment","Infrastructure"]
df=df.reindex(columns=columns_titles)

# 获取图片本地地址(图片可在)
flag_paths = list(Path("pic/country").glob("*.png"))
country_to_flagpath = {p.stem: p for p in flag_paths}

# 将排名改为整数
df["Rank"] = df["Rank"].round().astype(int)

# 新增Flag列,为对应的路径地址
df.insert(0, "Flag", df["Location"].apply(lambda x: country_to_flagpath.get(x)))

# 将City转为索引
df = df.set_index("City")

# 列重命名
df.rename(columns={'Culture_Environment': 'Environment'}, inplace=True)

df.head()

绘制基础的表格

python 复制代码
# 将后5列分为两大类
basic_services_cols = ["Stability", "Healthcare", "Education"]
infrastructure_env_cols = ["Environment", "Infrastructure"]

## 自定义各列
col_defs = (
    [
        ColumnDefinition(
            name="Flag",
            title="",
            textprops={"ha": "center"},
            width=0.5,
            plot_fn=circled_image,
        ),
        ColumnDefinition(
            name="City",
            textprops={"ha": "left", "weight": "bold"},
            width=1.5,
        ),
        ColumnDefinition(
            name="Location",
            textprops={"ha": "center"},
            width=0.75,
        ),
         ColumnDefinition(
            name="Rank",
            textprops={"ha": "center"},
            width=0.75,
        ),
         ColumnDefinition(
            name="Index",
            textprops={"ha": "center"},
            width=0.75,
        ),
        ColumnDefinition(
            name="Stability",
            width=0.75,
            textprops={
                "ha": "center",
                "bbox": {"boxstyle": "circle", "pad": 0.35},
            },
            cmap=normed_cmap(df["Stability"], cmap=matplotlib.cm.PiYG, num_stds=4),
            group="Quality of Life",
        ),
        ColumnDefinition(
            name="Healthcare",
            width=0.75,
            textprops={
                "ha": "center",
                "bbox": {"boxstyle": "circle", "pad": 0.35},
            },
            cmap=normed_cmap(df["Healthcare"], cmap=matplotlib.cm.PiYG, num_stds=4),
            group="Quality of Life",
        ),
         ColumnDefinition(
            name="Education",
            width=0.75,
            textprops={
                "ha": "center",
                "bbox": {"boxstyle": "circle", "pad": 0.35},
            },
            cmap=normed_cmap(df["Education"], cmap=matplotlib.cm.PiYG, num_stds=4),
            group="Quality of Life",
        ),
          ColumnDefinition(
            name="Environment",
            width=0.75,
            textprops={
                "ha": "center",
                "bbox": {"boxstyle": "circle", "pad": 0.35},
            },
            cmap=normed_cmap(df["Environment"], cmap=matplotlib.cm.PiYG, num_stds=4),
            group="Environment",
        ),
             ColumnDefinition(
            name="Infrastructure",
            width=0.75,
            textprops={
                "ha": "center",
                "bbox": {"boxstyle": "circle", "pad": 0.35},
            },
            cmap=normed_cmap(df["Infrastructure"], cmap=matplotlib.cm.PiYG, num_stds=4),
            group="Environment",
        ),
    ])
python 复制代码
# 修改字体和框边界
plt.rcParams["font.family"] = ["DejaVu Sans"]
plt.rcParams["savefig.bbox"] = "tight"

# 布局
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": "-"},
)

# 标题
header_text = "\n THE GLOBAL LIVEABILITY INDEX 2023"
header_props = {'fontsize': 18, 'fontweight': 'bold', 'va': 'center', 'ha': 'center'}
# 调整 y 坐标以使标题更靠近表格
plt.text(0.5, 0.91, header_text, transform=fig.transFigure, **header_props)

# 副标题
subtitle_text = "\n The Table visualizes a list of the Top 10 and Bottom 10 cities to Live in 2023. \n It rates living conditions in 173 cities across these five categories: stability, health care, culture and environment, education and infrastructure."
subtitle_props = {'fontsize': 14, 'va': 'center', 'ha': 'center', 'color': 'gray'}
plt.text(0.5, 0.89, subtitle_text, transform=fig.transFigure, **subtitle_props)

# 脚注
footer_text = "Source: The Economist Intelligence Unit • Visual and Analysis: Fortune Uwha"
footer_props = {'fontsize': 14, 'va': 'center', 'ha': 'center'}
# 调整 y 坐标以使页脚更靠近图形底部
plt.text(0.5, 0.09, footer_text, transform=fig.transFigure, **footer_props)

# 加载logo图片
logo_path = "pic/table_log.png"
logo = Image.open(logo_path)
# 调整图片尺寸
new_logo_size = (180, 100) 
logo = logo.resize(new_logo_size)
# 转为array
logo = np.array(logo)
# 将徽标放置在页面右侧
xo = 0.5 
yo = 0.09

plt.figimage(logo, xo=xo, yo=yo, origin='upper')

plt.show()

参考:Publication ready table with plottable

共勉~

相关推荐
IVEN_11 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang12 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮12 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling12 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮15 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽16 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
柳杉1 天前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python