首页/在线代码库/figure_style.py

figure_style.py

matplotlib 中文字体配置 + 统一绘图样式。

Python 34 行 系列:公共工具 🔒 源码仅供在线学习,不提供文件下载
完整源码 · 在线查看figure_style.py
12345678910111213141516171819202122232425262728293031323334
"""matplotlib 中文字体配置 + 统一绘图样式。"""
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager

CJK_CANDIDATES = [
    "Microsoft YaHei", "SimHei", "SimSun", "Noto Sans CJK SC",
    "Source Han Sans SC", "WenQuanYi Zen Hei",
]

_configured = False


def configure():
    global _configured
    if _configured:
        return
    available = {f.name for f in font_manager.fontManager.ttflist}
    for name in CJK_CANDIDATES:
        if name in available:
            plt.rcParams["font.sans-serif"] = [name, "DejaVu Sans"]
            break
    plt.rcParams["axes.unicode_minus"] = False
    _configured = True


def figures_dir():
    return os.path.join(os.path.dirname(__file__), "..", "figures")


configure()