使用matplotlib或seaborn中文显示异常问题

matplotlib中文显示异常问题

文章大部分内容是网上找的解决办法,最后一步网上说得有点不清楚,这里做个总结

1.在python中执行命令,找到matplotlibc文件的路径

 import matplotlib
 print(matplotlib.matplotlib_fname())
 # 结果如下 ubuntu环境
 /home/alien/.local/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc

2.下载SimHei.ttf文件下载地址(windows电脑可以去fonts系统目录下找),将文件放到ttf文件夹里,相对路径如下

matplotlib/mpl-data/fonts/ttf/SimHei.ttf

3.修改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)

结果如下:xx

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值