Python matplotlib 画图中文显示方框怎么修复?
Python matplotlib 画图中文显示方框怎么修复?
问题分析
在 Python 里用 matplotlib 画图时,中文标题或坐标轴标签显示成方框(□□□),通常是因为默认字体(如 DejaVu Sans)不包含中文字形。课程作业、实验报告、数据可视化项目里都很常见。
本质就一件事:让 matplotlib 使用你系统里已有的中文字体,并顺手处理负号显示。
建议优先试方法一(改两行rcParams即可);只有系统里确实没有中文字体时,再用方法二下载开源字体。
排查步骤
1.确认系统是否有中文字体
- Windows:看C:/Windows/Fonts/是否有simhei.ttf(黑体)或msyh.ttc(微软雅黑)
- macOS:看/System/Library/Fonts/或/Library/Fonts/
- Linux:运行fc-list :lang=zh查看已安装的中文字体
2.确认 matplotlib 能否识别该字体
import matplotlib.font_manager as fm fonts = [f.name for f in fm.fontManager.ttflist if 'SimHei' in f.name or 'Microsoft YaHei' in f.name] print(fonts)若输出为空,说明当前环境字体列表里没有这些字体,需要安装字体或走方法二。
3.检查代码是否同时设置了字体和负号
只写font.sans-serif而不写axes.unicode_minus = False,中文可能正常但负号仍显示异常。
示例代码
方法一:使用系统自带字体(Windows / macOS 优先试这个)
import matplotlib.pyplot as plt # Windows 常用 SimHei 或 Microsoft YaHei plt.rcParams['font.sans-serif'] = ['SimHei'] # 或 ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 负号正常显示 x = [1, 2, 3, 4] y = [10, 20, 15, 25] plt.plot(x, y, marker='o') plt.title('中文标题测试') plt.xlabel('横轴(单位)') plt.ylabel('纵轴(数值)') plt.show()方法二:安装开源中文字体(Linux 或系统无中文字体时)
思源黑体免费开源。下载后注册到 matplotlib:
import matplotlib.pyplot as plt import matplotlib.font_manager as fm import urllib.request import os font_url = ( 'https://github.com/adobe-fonts/source-han-sans/raw/release/OTF/' 'SimplifiedChinese/SourceHanSansSC-Regular.otf' ) font_path = 'SourceHanSansSC-Regular.otf' if not os.path.exists(font_path): urllib.request.urlretrieve(font_url, font_path) fm.fontManager.addfont(font_path) font_prop = fm.FontProperties(fname=font_path) plt.rcParams['font.family'] = font_prop.get_name() plt.rcParams['axes.unicode_minus'] = False plt.plot([1, 2, 3], [4, 5, 6]) plt.title('中文标题', fontproperties=font_prop) plt.xlabel('横轴', fontproperties=font_prop) plt.ylabel('纵轴', fontproperties=font_prop) plt.show()若 GitHub 下载慢,可手动下载字体文件放到脚本同目录,再运行上面代码。
运行说明
1.环境:Python 3.6+,pip install matplotlib
2.改完字体仍显示方框:清除 matplotlib 字体缓存后重启 Python:
import matplotlib print(matplotlib.get_cachedir()) # 删除该目录下 fontlist-*.json,再重新运行绘图代码3.验证:图表标题、坐标轴中文应正常显示,不再是方框。
常见坑
1.字体名写错
- 正确:'SimHei'、'Microsoft YaHei'
- 错误:'simhei'(大小写敏感)、直接写'宋体'(应使用字体注册名)
2.未清缓存
修改rcParams后仍用旧缓存。删~/.matplotlib/fontlist-*.json并重启解释器。
3.Linux 缺字体
sudo apt-get install fonts-wqy-zenheiplt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei'] plt.rcParams['axes.unicode_minus'] = False4.Jupyter Notebook 不生效
先执行:
%matplotlib inline import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False5.负号变方块
补上plt.rcParams['axes.unicode_minus'] = False。
按上面步骤仍显示方框,可以把操作系统、matplotlib 版本、完整报错或截图发评论区,我帮你看。