跳转到内容

File:WPVG Newsletter 202507 Feature Graph 2 (zh-cn).png

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

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

摘要

[编辑]
文件信息
描述

電子遊戲專題簡訊2025年7月刊專題報導插圖——專題品質統計

來源

#製圖代碼

日期

2015-06-06

作者

SuperGrey et al.

授權許可
(重用此文件)

參見下方。

其他版本

授權協議

[编辑]
SuperGrey et al.,本作品的著作權持有者,決定用以下授權條款發佈本作品:
您可以選擇您想要的授權條款。

製圖代碼

[编辑]
"""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": "專題十周年條目品質概況",
        "hans_header": "专题十周年条目品质概况",
        "path_pattern": "WPVG Newsletter 202507 Feature Graph 2 (zh-{}).png",
    }
    # https://web.archive.org/web/20150606095543/
    # http://zh.wikipedia.org/wiki/Category:文件级电子游戏条目
    data = {
        "fa": 9,
        "ga": 25,
        "b": 94,
        "c": 285,
        "start": 1_543,
        "list": 233,
        "stub": 1_694,
        "unassessed": 62,
    }
    # 修改上面的资料

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

文件历史

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

日期/时间缩⁠略⁠图大小用户备注
当前2025年5月30日 (五) 14:102025年5月30日 (五) 14:10版本的缩略图1,765 × 1,215​(129 KB)For Each element In group ... Next留言 | 贡献
2025年5月30日 (五) 13:432025年5月30日 (五) 13:43版本的缩略图1,904 × 1,215​(118 KB)For Each element In group ... Next留言 | 贡献{{Esoteric file}} {{Information |Description=電子遊戲專題簡訊2025年7月刊專題報導插圖——專題品質統計 |Source=<syntaxhighlight lang="python> """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_MAPPI…

元数据