在Linux服务器上调用matplotlib库时报错:
findfont: Generic family 'sans-serif' not found because none of the following families were found: SimHei
UserWarning: Glyph 19981 (\N{CJK UNIFIED IDEOGRAPH-4E0D}) missing from font(s) DejaVu Sans.
解决方案:
下载并安装SimHei字体:
下载SimHei字体文件(simhei.ttf)。
simhei.ttf下载-ttf-字体分类-发现字体-求字体网https://www.qiuziti.com/fontlist2?id=673807
创建字体目录:
在/usr/share/fonts/目录下创建一个新的目录用于存放SimHei字体:
mkdir -p /usr/share/fonts/truetype/simhei
复制字体文件到字体目录:
将下载的simhei.ttf文件复制到您刚刚创建的目录中:
cp simhei.ttf /usr/share/fonts/truetype/simhei/
更新字体缓存:
更新系统的字体缓存,使新安装的字体生效:
sudo fc-cache -fv
确认SimHei字体是否已正确安装:
通过以下命令来检查系统中是否已经安装了SimHei字体:
fc-list | grep SimHei
如果命令返回了SimHei字体的信息,说明字体已安装。
清除matplotlib字体缓存:
删除缓存目录(通常位于~/.cache/matplotlib
)中的所有文件:
rm -rf ~/.cache/matplotlib
然后重新运行代码,matplotlib将会重新加载字体设置
运行代码
运行代码,检查是否能够正确显示中文字符。
import matplotlib.pyplot as plt
# 设置matplotlib的字体,确保中文可以显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 'SimHei' 是一种常用的中文字体
plt.rcParams['axes.unicode_minus'] = False # 正确显示负号
# 绘制饼图
_, ax = plt.subplots()
ax.pie(values, labels=categories, autopct='%1.1f%%')
# 添加标题
ax.set_title('title')
# 保存图表为PNG文件
plt.savefig(output_file)