当前位置: 首页 > news >正文

matplotlib 中文显示异常的修复方法

这个问题很常见

问题原因

1. 字体缓存污染

matplotlib 在第一次运行时创建字体缓存,如果之前有错误的字体配置或损坏的缓存,会导致后续所有绘图都使用错误的字体设置。

2. 缓存不更新

即使你后来添加了正确的中文字体,matplotlib 可能仍然使用旧的缓存文件,不会自动检测新字体。

3. 环境配置冲突

在 Jupyter/云平台环境中,多个用户或会话可能共享或冲突的缓存配置。

以后注意事项

1. 字体设置最佳实践

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import osdef safe_chinese_plot():"""安全的中文绘图函数"""# 方法1:先尝试系统字体plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'DejaVu Sans', 'Arial']plt.rcParams['axes.unicode_minus'] = False# 如果系统字体不行,使用自定义字体font_path = './simsun.ttc'if os.path.exists(font_path):font_prop = fm.FontProperties(fname=font_path)# 使用 fontproperties 参数plt.title('标题', fontproperties=font_prop)plt.xlabel('X轴', fontproperties=font_prop)else:plt.title('标题')plt.xlabel('X轴')

2. 项目初始化脚本

# init_plot.py - 每个项目开始前运行
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import osdef init_chinese_font():"""初始化中文字体设置"""# 清除可能的缓存问题cache_dir = os.path.join(os.path.expanduser('~'), '.cache', 'matplotlib')if os.path.exists(cache_dir):import shutilshutil.rmtree(cache_dir)print("已清除matplotlib缓存")# 重新加载字体管理器fm._load_fontmanager(try_read_cache=False)# 设置字体font_path = './simsun.ttc'if os.path.exists(font_path):# 添加自定义字体fe = fm.FontEntry(fname=font_path, name='MySimSun')fm.fontManager.ttflist.insert(0, fe)plt.rcParams['font.family'] = ['MySimSun', 'WenQuanYi Micro Hei']else:plt.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei', 'DejaVu Sans']plt.rcParams['axes.unicode_minus'] = Falseprint("中文字体初始化完成")# 在项目开始时调用
init_chinese_font()

3. 环境检查脚本

def check_font_environment():"""检查字体环境"""import matplotlib.font_manager as fmimport osprint("=== 字体环境检查 ===")# 检查缓存目录cache_dir = os.path.join(os.path.expanduser('~'), '.cache', 'matplotlib')print(f"缓存目录: {cache_dir}")print(f"缓存存在: {os.path.exists(cache_dir)}")# 检查可用中文字体chinese_fonts = []for font in fm.fontManager.ttflist:font_name = font.name.lower()if any(keyword in font_name for keyword in ['chinese', 'song', 'hei', 'kai', 'micro', 'wenquan']):chinese_fonts.append(font.name)print(f"可用中文字体: {list(set(chinese_fonts))}")# 检查自定义字体custom_font = './simsun.ttc'print(f"自定义字体存在: {os.path.exists(custom_font)}")return len(chinese_fonts) > 0# 在绘图前运行检查
if check_font_environment():print("字体环境正常")
else:print("警告: 字体环境可能有问题")

4. 可靠的绘图模板

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import osclass ChinesePlot:def __init__(self, font_path='./simsun.ttc'):self.font_path = font_pathself.font_prop = Noneif os.path.exists(font_path):self.font_prop = fm.FontProperties(fname=font_path)def safe_text(self, text, **kwargs):"""安全地添加中文文本"""if self.font_prop:kwargs['fontproperties'] = self.font_propreturn kwargsdef plot(self):"""示例绘图方法"""plt.figure(figsize=(10, 6))# 安全设置标题和标签plt.title('中文标题', **self.safe_text('中文标题', fontsize=16))plt.xlabel('X轴标签', **self.safe_text('X轴标签', fontsize=14))plt.ylabel('Y轴标签', **self.safe_text('Y轴标签', fontsize=14))plt.text(0.5, 0.5, '中文文本', **self.safe_text('中文文本', fontsize=12, ha='center'))plt.grid(True)plt.show()# 使用
plotter = ChinesePlot()
plotter.plot()

5. 常见预防措施

  1. 在Docker/云环境中:在容器启动时清除字体缓存
  2. 在CI/CD中:在流水线中添加字体缓存清理步骤
  3. 团队项目中:共享字体初始化脚本
  4. 版本控制:将字体文件和初始化脚本纳入版本管理

6. 快速修复命令

# 当遇到中文乱码时,快速执行这个单元格
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import os
import shutil# 清除缓存
cache_dir = os.path.join(os.path.expanduser('~'), '.cache', 'matplotlib')
if os.path.exists(cache_dir):shutil.rmtree(cache_dir)# 重新加载
fm._load_fontmanager(try_read_cache=False)
plt.rcParams.update({'font.sans-serif': ['WenQuanYi Micro Hei']})
print("字体缓存已重置")

总结:matplotlib 字体缓存是个常见坑点,在云平台、容器等环境中尤其要注意。建议在每个项目开始前都运行字体初始化检查。

http://www.hn-smt.com/news/33434/

相关文章:

  • 2025年大型活动遮阳蓬生产商排行榜
  • 2025年提分系统平台口碑排行
  • 详细介绍:米家智能家居方案(租房版)
  • react 生命周期函数有哪些?
  • 2025年做工精细的前置过滤器排行
  • Python3 Pickle 模块详解
  • 2025杭州计量泵制造厂推荐排行
  • Mysql常问面试题 - 教程
  • 2025年大型深孔钻镗床厂家推荐排行
  • AI元人文:构建文明级认知纠缠体的操作系统
  • 2025 年 11 月电缆厂家权威推荐榜:国标/国网入围/南网入围/铜芯/纯铜/铝合金/光伏/新能源/控制/拖链/铠装电缆厂家精选
  • AI编程软件三强:谁才是2025年你的最佳AI编程软件拍档?
  • 编程小白的福音:十款AI编程助手助你轻松入门
  • 如何计算并发及机器
  • 第22天(简单题中等题 二分查找)
  • In the name of capitalists
  • 基于SpringBoot+Vue的线上一流课程教学辅助系统管理系统设计与实现【Java+MySQL+MyBatis完整源码】 - 指南
  • 2025 ICPC 南京区域赛游记
  • CF round vp 选记
  • *题解:P5278 算术天才⑨与等差数列
  • 2025浸没式/液冷超充/新能源车/超充站领域实力厂家排行榜:中碳创新领衔,四大品牌重塑新能源车补能生态
  • ##题解##洛谷P1578##最大子矩形 扫描线法
  • 重练算法(代码随想录版) day 7 -哈希表part2
  • 实用指南:根据用户行为数据中的判断列表在 Elasticsearch 中训练 LTR 模型
  • chatTTS源码版本地部署踩的坑
  • 第一讲机器学习基础
  • 当世人 逐渐将英雄遗忘 我最终展露了疯狂 与烧灼许久的欲望 已无人描绘 我的画像
  • 鸿蒙NEXT系列之精析NDK UI API(节点增删和属性设置) - 实践
  • 【JVS更新日志】开源框架升级vue 3、低代码、企业计划、智能BI及其他产品迎来新版本! - 实践
  • Linux内核架构浅谈26-Linux实时进程调度:优先级反转与解决实用的方案