跳转到内容

文件:WPVG Newsletter 202201 Feature Graph 1 (zh-cn).png

维基百科,自由的百科全书

原始文件 (1,804 × 1,215像素,文件大小:160 KB,MIME类型:image/png

摘要

[编辑]
文件信息
描述

电子游戏专题简讯2022年1月刊专题报导插图——2021年年终条目质量概况

来源
展开看代码
"""Created by [[User:SuperGrey]] with modifications."""

from collections import OrderedDict
from collections.abc import Mapping
from typing import Literal, NamedTuple, TypedDict

from matplotlib import pyplot as plt
from matplotlib.lines import Line2D

# For drawing figures.
FIG_WIDTH = 10  # hpx
FIG_HEIGHT = 5  # hpx
MAGIC_PERCENTAGE = 0.05  # Don't know how it works.
FONT_MAPPING = {
    "tw": "Source Han Sans TC",
    "hk": "Source Han Sans HC",
    "cn": "Source Han Sans SC",
}

type ChineseVariants = Literal["cn", "hk", "tw"]


class GradeConfig(NamedTuple):
    """Configuration for an article quality grade."""

    hant_name: str
    hans_name: str
    color: str


class GradeInfo(NamedTuple):
    """Information about a specific article quality grade."""

    name: str
    color: str
    count: int


class FigureConfigDict(TypedDict):
    """Configuration for generating a figure."""

    data: Mapping[str, list[str | int]]
    header: str
    path: str
    chinese_font: str


GRADES = OrderedDict(
    [
        ("fa", GradeConfig("典範級", "典范级", "#9CBDFF")),
        ("fl", GradeConfig("特色列表級", "特色列表级", "#9CBDFF")),
        ("ga", GradeConfig("優良級", "优良级", "#66FF66")),
        ("b", GradeConfig("乙級", "乙级", "#B2FF66")),
        ("bl", GradeConfig("乙級列表級", "乙级列表级", "#B2FF66")),
        ("c", GradeConfig("丙級", "丙级", "#FFFF66")),
        ("cl", GradeConfig("丙級列表級", "丙级列表级", "#FFFF66")),
        ("start", GradeConfig("初級", "初级", "#FFAA66")),
        ("list", GradeConfig("列表級", "列表级", "#C7B1FF")),
        ("stub", GradeConfig("小作品級", "小作品级", "#FFA4A4")),
        ("sl", GradeConfig("小列表級", "小列表级", "#FFA4A4")),
        ("unassessed", GradeConfig("未評級", "未评级", "#EEEEEE")),
    ],
)


def handle_data(
    stat: Mapping[str, int | None],
    /,
    variant: ChineseVariants,
) -> dict[str, list[int] | list[str]]:
    """Pre-process statistical data for visualization."""

    counts = []
    colors = []
    names = []
    for code, grade in GRADES.items():
        try:
            count = stat[code]
        except KeyError:
            continue
        counts.append(count)
        name = grade.hans_name if variant == "cn" else grade.hant_name
        names.append(name)
        color = grade.color
        colors.append(color)

    total = sum(counts)
    labels, explodes = [], []
    for count in counts:
        label, explode = "", 0
        if (percentage := count / total) > MAGIC_PERCENTAGE:
            label = f"{percentage * 100:.1f}%"
            explode = MAGIC_PERCENTAGE
        labels.append(label)
        explodes.append(explode)

    return {
        "names": names,
        "counts": counts,
        "labels": labels,
        "colors": colors,
        "explodes": explodes,
    }


def handle_config(
    stat: Mapping[str, int],
    variant: ChineseVariants,
    /,
    path_pattern: str,
    hant_header: str,
    hans_header: str,
) -> FigureConfigDict:
    """Create a figure configuration."""

    header = hans_header if variant == "cn" else hant_header
    data = handle_data(stat, variant)
    path = path_pattern.format(variant)
    chinese_font = FONT_MAPPING[variant]
    return FigureConfigDict(
        data=data, header=header, path=path, chinese_font=chinese_font
    )


def save_figure(config: FigureConfigDict) -> None:
    """Generate and save a pie chart as a png file."""

    data = config["data"]
    plt.rc(
        "font",
        family=(
            "DejaVu Sans",
            config["chinese_font"],
        ),
    )

    _, ax = plt.subplots(figsize=(FIG_WIDTH, FIG_HEIGHT))
    ax.pie(
        data["counts"],
        colors=data["colors"],
        explode=data["explodes"],
        labels=data["labels"],
        labeldistance=0.5,
        startangle=90,
        textprops={"rotation_mode": "anchor", "ha": "center", "va": "center"},
    )

    legend_data = zip(
        data["names"],
        data["colors"],
        data["counts"],
        strict=False,
    )
    legend_handles = [
        Line2D(
            [0],
            [0],
            marker="o",
            color="w",
            label=f"{d[0]}{d[2]}",  # noqa: RUF001
            markersize=10,
            markerfacecolor=d[1],
        )
        for d in legend_data
    ]
    ax.legend(
        handles=legend_handles,
        loc="upper left",
        bbox_to_anchor=(0.95, 0.8),
        frameon=False,
    )
    plt.figtext(
        x=0.705,
        y=0.76,
        s=config["header"],
        fontsize=12,
        verticalalignment="top",
        fontweight="bold",
        backgroundcolor="white",
    )
    plt.savefig(
        config["path"],
        dpi=300,
        bbox_inches="tight",
    )


def mian() -> None:
    """As you know, the function name is correct."""

    # 修改下面的资料
    info = {
        "hant_header": "2021年年終條目品質概況",
        "hans_header": "2021年年终条目品质概况",
        "path_pattern": "WPVG Newsletter 202201 Feature Graph 1 (zh-{}).png",
    }
    data = {
        "fa": 14,
        "fl": 9,
        "ga": 118,
        "b": 140,
        "bl": 5,
        "c": 770,
        "cl": 25,
        "start": 3_328,
        "list": 319,
        "stub": 5_410,
        "unassessed": 309,
    }
    # 修改上面的资料

    for variant in ("tw", "hk", "cn"):
        config = handle_config(
            data,
            variant,
            path_pattern=info["path_pattern"],
            hant_header=info["hant_header"],
            hans_header=info["hans_header"],
        )
        save_figure(config)


if __name__ == "__main__":
    mian()
日期

2023年10月2日

作者

User:BlackShadowG提供资料,User:SuperGrey提供代码(有改动)

授权许可
(重用此文件)
w:zh:知识共享

署名 相同方式共享

本文件采用知识共享署名-相同方式共享 3.0 未本地化版本许可协议授权。
署名: BlackShadowG
您可以自由地:
  • 共享 – 复制、发行并传播本作品
  • 修改 – 改编作品
惟须遵守下列条件:
  • 署名 – 您必须对作品进行署名,提供授权条款的链接,并说明是否对原始内容进行了更改。您可以用任何合理的方式来署名,但不得以任何方式表明许可人认可您或您的使用。
  • 相同方式共享 – 如果您再混合、转换或者基于本作品进行创作,您必须以与原先许可协议相同或相兼容的许可协议分发您贡献的作品。

其他版本

文件历史

点击某个日期/时间查看对应时刻的文件。

日期/时间缩⁠略⁠图大小用户备注
当前2025年5月29日 (四) 15:342025年5月29日 (四) 15:34版本的缩略图1,804 × 1,215​(160 KB)For Each element In group ... Next留言 | 贡献
2023年10月2日 (一) 15:052023年10月2日 (一) 15:05版本的缩略图501 × 303​(34 KB)Lopullinen留言 | 贡献{{Esoteric file}} == 摘要 == {{Information |Description = 電子遊戲專題簡訊2022年1月刊專題報導插圖——2021年年终条目质量概况 |Source = <syntaxhighlight lang="wikitext">{{Graph:Chart|width=100|height=100|type=pie|legend=2021年年终条目质量概况|x=典范级:14,特色列表级:9,优良级:118,乙级:140,乙级列表级:5,丙级:770,丙级列表级:25,初级:3328,列表级:319,小作品级:5410,未评级:309|y1=14,9,118,140,5,770,25,3328,319,5410,309|colors=#6699ff,#6699ff,#66ff66,#b2ff66,#b2ff66,#ffff66,#ffff66,#ffaa66,#aa88ff,#ff6666,#F5F5F5}} </syntaxhighlight> |Date = 2023年10月2日 |Author= [[User:BlackShadow…

元数据