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文件,就不会乱码了

相关推荐
茶栀(*´I`*)5 天前
【Python数据可视化】Matplotlib从零到精通:图表核心解剖、多子图布局与三大经典图表实战
python·信息可视化·matplotlib
jzshmyt16 天前
我用 Python 从零“生成“了一个宇宙,然后让它观察自己(v14)
人工智能·pytorch·python·numpy·matplotlib·空间计算·scipy
小葱炖豆腐21 天前
python绘制excel折线图
python·excel·numpy·pandas·matplotlib
七灵微21 天前
【AI】代码实战- 基于时间序列的轴承检测1
人工智能·机器学习·ai·pandas·matplotlib
微小冷1 个月前
pyqt+matplotlib多进程图像刷新
pyqt·matplotlib·进程通信·多进程·queue·process
㳺三才人子2 个月前
初探 Data Analysis - Matplotlib
python·plotly·pandas·matplotlib
菜冻鱼2 个月前
Python-sklearn-特征工程
开发语言·人工智能·python·机器学习·numpy·matplotlib·sklearn
cui_ruicheng2 个月前
Python数据分析(十一):数据可视化与 Matplotlib
python·信息可视化·数据分析·matplotlib
编程阿峰2 个月前
Python 环境配置(二)安装jupyter、matplotlib、numpy库
开发语言·python·jupyter·numpy·matplotlib
人工智能时代 准备好了吗2 个月前
Python + Jinja2 + Matplotlib:AI回答采集报告自动化生成实现
人工智能·python·matplotlib