文章大部分内容是网上找的解决办法,最后一步网上说得有点不清楚,这里做个总结
1.在python中执行命令,找到matplotlibc文件的路径import matplotlib print(matplotlib.matplotlib_fname()) # 结果如下 ubuntu环境 /home/alien/.local/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc2.下载SimHei.ttf文件下载地址(windows电脑可以去fonts系统目录下找),将文件放到ttf文件夹里,相对路径如下
matplotlib/mpl-data/fonts/ttf/SimHei.ttf3.修改matplotlibrc文件
# 可用ctrl+f查找位置,修改如下(记得 把‘#’去除掉):
font.family:sans-serif
font.sans-serif:SimHei,Bitstream ....#(把SimHei 加到最前面)
axes.unicode_minus:False #(解决-报错的问题)
4.重新加载matplotlib
- 第一种方法
from matplotlib.font_manager import _rebuild _rebuild() #重新加载 #若报错情况如下,则采用第二种方法 #ImportError: cannot import name '_rebuild' from 'matplotlib.font_manager'....
- 第二种方法
import shutil import matplotlib shutil.rmtree(matplotlib.get_cachedir()) #操作完,直接重启matplotlib,问题就可以解决
另外,如果使用seaborn,同样会中文无法显示,我猜测原因是seaborn采用了和matplotlib相同的fonts,这里需要手动加载字体,下面是一个例子
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 引用了seaborn后,图片有了背景,但会报找不到字符,中文无法显示,需手动添加
sns.set_theme(style="darkgrid")
# 两种添加字符均可
sns.set(font="SimHei")
#plt.rcParams['font.sans-serif'] = 'SimHei'
x = np.arange(-5, 5, 0.1)
y = np.sin(x)
talor_sinx = x - (x**3)/np.math.factorial(3) +
(x**5)/np.math.factorial(5) -
(x**7)/np.math.factorial(7)
plt.title("sinx和其泰勒展开的对比")
plt.plot(x, y)
plt.plot(x, talor_sinx)
结果如下:



