mac OS matplotlib missing from font(s) DejaVu Sans

如果能搜索到这篇文章,我猜你遇到了和我一样的问题:matplotlib绘图中文乱码。如下:

出现这个问题的原因是 :matplotlib使用的字体列表中默认没有中文字体。
这里说一种解决方案 :我们可以在文件中手动指定matplotlib使用的字体

在python文件中指定matplotlib使用的字体,如下:

python 复制代码
plt.rcParams['font.sans-serif']=['STFangsong'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号

完整代码:

python 复制代码
from pylab import mpl
from sklearn.tree import DecisionTreeClassifier, plot_tree
import numpy as np
import matplotlib.pyplot as plt

#手动指定matplotlib使用的字体
plt.rcParams['font.sans-serif']=['STFangsong'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号

# 创建数据集
X = np.array([
    [0, 2, 0],  # 晴天,高温,无风
    [1, 1, 1],  # 阴天,中温,微风
    [2, 0, 2],  # 雨天,低温,强风
    # ... 添加更多样本以增加模型的准确性
])
y = np.array([0, 1, 2])  # 分别对应去野餐、去博物馆、在家看书

# 初始化决策树模型,设置最大深度为5
clf = DecisionTreeClassifier(max_depth=5, random_state=42)

# 训练模型
clf.fit(X, y)

# 可视化决策树
plt.figure(figsize=(20, 10))
plot_tree(clf, filled=True, feature_names=["天气状况", "温度", "风速"], class_names=["去野餐", "去博物馆", "在家看书"], rounded=True, fontsize=12)
plt.show()

然后清除一下matplotlib的缓存

powershell 复制代码
rm -rf ~/.matplotlib

之后再重新执行python文件,就不会乱码了

相关推荐
Jay_272 天前
cloudstudio腾讯云:matplotlib 设置中文字体
腾讯云·matplotlib
Gyoku Mint7 天前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
搏博9 天前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
Code_流苏12 天前
Python趣学篇:交互式词云生成器(jieba + Tkinter + WordCloud等)
python·pillow·matplotlib·tkinter·wordcloud·jieba分词·词云生成器
AndrewHZ14 天前
【图像处理入门】2. Python中OpenCV与Matplotlib的图像操作指南
图像处理·python·opencv·计算机视觉·matplotlib·图像操作
无闻墨客15 天前
数据可视化--使用matplotlib绘制高级图表
python·机器学习·信息可视化·matplotlib·可视化·数据可视化
Echo-J15 天前
数据可视化(第4、5、6次课)
python·信息可视化·matplotlib·数据可视化
ayas1231918 天前
numpy与matplotlib学习——数据可视化入门
学习·numpy·matplotlib
zhangfeng113318 天前
Python 和 matplotlib 保存图像时,确保图像的分辨率和像素符合特定要求(如 64x64),批量保存 不溢出内存
开发语言·python·matplotlib
李昊哲小课21 天前
matplotlib基本绘图
人工智能·数据分析·matplotlib·数据可视化·pyecharts·seaborn