跳至內容

檔案: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:34於 2025年5月29日 (四) 15:34 版本的縮圖1,804 × 1,215​(160 KB)For Each element In group ... Next對話 | 貢獻
2023年10月2日 (一) 15:05於 2023年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…

詮釋資料