惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
U
Unit 42
H
Help Net Security
博客园_首页
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
aimingoo的专栏
aimingoo的专栏
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
S
Security @ Cisco Blogs
M
MIT News - Artificial intelligence
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
Spread Privacy
Spread Privacy
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
V
Vulnerabilities – Threatpost
WordPress大学
WordPress大学
C
Cisco Blogs
G
Google Developers Blog
N
News and Events Feed by Topic
P
Palo Alto Networks Blog
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
博客园 - 聂微东
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
O
OpenAI News
云风的 BLOG
云风的 BLOG
IT之家
IT之家
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
小众软件
小众软件
Scott Helme
Scott Helme
大猫的无限游戏
大猫的无限游戏
L
LINUX DO - 最新话题
Microsoft Azure Blog
Microsoft Azure Blog
Simon Willison's Weblog
Simon Willison's Weblog
N
News and Events Feed by Topic
F
Fortinet All Blogs
The Last Watchdog
The Last Watchdog

StudyingLover's Blog

Diffusion Policy笔记 rwkv笔记 act笔记 nanovllm-block_manager opencode多智能体 nanobot-pre-train nanobot-rl nanobot-sft nanobot-checkpoint_manager nanobot-gpt nanobot-mid-train Vision Mamba (Vim)笔记 BPE演示 最后一遍学习Transformer YOLOv5 目标检测笔记 下载根服务器解析记录 Dynaseal A Backend-Controlled LLM API Key Distribution Scheme with Constrained Invocation Parameters 判断链表有环 王道25数据结构勘误 关于perplexity的open-sourcing-r1-1776 AI为什么不像人类一样进行多轮对话 新博客改造日记和功能测试 linuxqq只显示登陆背景图 数字设计和计算机体系结构(机械工业出版社)勘误(自制) Dynaseal:面向未来端侧llm agent的llm api key分发机制 A Definitive Guide to Markdown Style This post is using MDX, Where you can embed JSX and Astro components RT-Patch学习 pydantic实现的LLM ReAct fastapi 和 uvicorn 设置监听 ipv6 pydantic+openai+json 控制大模型输出的最佳范式 解决 Matplotlib Scatter 不支持 Marker 列表的问题:mscatter 实现 roofline model zhipuAI接口兼容openai 在docker部署fastapi宝塔里使用nginx反代套上cloudflare获取请求的真实ip clion搭建libbpf-bootstrap开发环境 coze+coze-discord-proxy+ChatNextWebUI实现AI自由 安卓内核时间使用的是UTC时间 colab运行google最新开源模型Gemma Sora技术报告 视频生成模型作为世界模拟器 笔记 archlinux flutter开发踩坑 fastapi集成google auth登录 linux下NTFS磁盘报错输入输出错误 Venn-Abers 预测器 基于Venn-Abers预测器的系统日志异常检测方法_顾兆军 手机平板远程访问kvm虚拟机的windows phi-2弱智吧测评 poe的gemini pro或是百度开发 google gemini api使用 google gemini api申请 构建用于复杂数据处理的高效UDP服务器和客户端 TruFor笔记和代码复现 深入分析:GitHub Trending 项目 "multipleWindow3dScene" pua大模型 ggml教程|mnist手写体识别量化推理 xgboost2.0最佳实践 xgboost使用GPU最佳实践 马踏棋盘 cloudlflare推理llama2 docker搭建elasticsearch并使用python连接 FreeU-文字生成图片的免费午餐笔记 使用xgboost的c接口推理模型 Archlinux使用CMake调用xgboost的c接口 m2cgen生成机器学习c语言推理代码 xgboost模型序列化存储并推理 speculative-sampling笔记 prompt2model笔记 RoboTAP笔记 自建obsidian同步服务 MediaPipe即将推出图像生成服务 Dual-Stream Diffusion Net for Text-to-Video Generation笔记 ViT在DDPM取代UNet(DiT) arch4edu搞崩了我的flutter LISA(推理分割)笔记 在终端绘制GPU显存使用曲线 GPTBot介绍 arch蓝牙无法连接 GPU部署llama-cpp-python(llama.cpp通用) 花式求GCD 使用llama构建一个蜜罐(前端) 使用llama构建一个蜜罐(后端) llama-cpp-python快速上手 快速上手llama2.c(更新版) Paper Gestalt笔记 DINO-v2笔记 快速上手llama2.c AnyDoor笔记 Archlinux安装scrcpy加载共享库出错 error while loading shared libraries:libusb-1.0.so.0:wrong ELF class:ELFCLASS32 npc_gzip笔记 python调用c++函数 Filesystem type ntfs3,ntfs not configured in kernel open_clip编码图像和文本 PicGo配置CloudflareR2图片储存 ArchlinuxGnome快捷键打开终端 clip-interrogator代码解析 GroundingDINO安装报错解决 2023华为鲲鹏畅想日暨西安高新国际会议中心零食午饭测评 RoboMaster开源仓库汇总(长期更新) 没有手都可以在腾讯云创建镜像 I3D笔记
matplotlib中文字体渲染
About the Author StudyingLover · 2023-12-05 · via StudyingLover's Blog

matplotlib中文字体渲染

matplotlib 在画图例的时候不可避免的需要使用中文字体,但是有的时候电脑自带的字体不能渲染中文,这就需要我们自己解决字体问题。

首先用一个代码看一下系统里的字体哪些可以正常渲染中文字体

import matplotlib.font_manager as font_manager
import matplotlib.pyplot as plt
import time

def find_chinese_fonts(test_string):
    """
    This function tests each available font to see if it can render the given Chinese string
    without causing any rendering issues or noticeable delays.
    """
    fonts = font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
    working_fonts = []

    for font in fonts:
        try:
            prop = font_manager.FontProperties(fname=font)
            plt.figure()
            start_time = time.time()
            plt.text(0.5, 0.5, test_string, fontproperties=prop, ha='center', va='center')
            plt.close()
            end_time = time.time()
            render_time = end_time - start_time

            # Check if the rendering time is less than a certain threshold (e.g., 0.5 seconds)
            if render_time < 5:
                working_fonts.append(font)

        except Exception as e:
            # If there's an error rendering with this font, skip it
            continue

    return working_fonts

# Test string: "不卡顿"
test_string = "不卡顿"
fonts = find_chinese_fonts(test_string)
fonts

假设输出了 '/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf'

使用这个字体的代码就是

from matplotlib.font_manager import FontProperties

# 创建一个FontProperties对象,指定字体文件路径
font = FontProperties(fname='/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf')

# 绘制散点图
plt.scatter([1,2,3], [4,5,6], color="red")

# 添加图例,使用指定的字体
plt.legend(["例子"], prop=font)

# 显示图像
plt.show()

假如代码没找到可用字体呢?

手动下载字体。以下是一些中文字体的官方下载页面或者信誉良好的资源:

  1. 思源宋体(Source Han Serif):
    • 官方GitHub页面: Adobe Fonts
    • 选择您需要的语言子集,例如简体中文(SC),并下载相应的 OTF 文件。
  2. 思源黑体(Source Han Sans):
    • 官方GitHub页面: Adobe Fonts
    • 同样地,选择您需要的语言子集,并下载 OTF 文件。
  3. 文泉驿正黑(WenQuanYi Zen Hei):
    • 官方网站: WenQuanYi
    • 可以直接下载 TTF 文件。

下载完成后然后font = FontProperties(fname='/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf') 引入即可。