linux服务器上的matplotlib中文字体设置问题(使用ttf文件)

如果本来就没有中文字体,必须先安装并配置字体,保证有中文字体ttf的文件

配置:修改matplotlibrc配置字体

1. 首先定位matplotlib的字体库路径(我使用python进行定位)

import matplotlib
matplotlib.matplotlib_fname()

2. 将中文字体文件**.ttf,拷贝到该目录的fonts/ttf下

3. 删除 matplotlib 缓存

cd ~/.cache/matplotlib
rm * -r

4. 修改matplotlibrc文件:修改font.sans-serif 加入中文字体

font.sans-serif     : Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif, ***(刚加的字体名字)

5. 重启程序或在 jupyter中restart the kernel

应用一:用plt.rcParams设置

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
plt.xlabel('测试')
plt.show()

应用二:用FontProperties,并指定字体文件

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname='/mnt/share/code/font/SimHei.ttf', size=20)
plt.title('测试', fontproperties=font)

参考

https://ask.hellobi.com/blog/safa/36673

  • 10
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Matplotlib设置中文字符的方法有两种: 1. 使用系统默认字体 Matplotlib 使用系统默认字体(如 Times New Roman)显示文本,如果需要在文本中使用中文字符,需要确保计算机已经安装了中文字体,然后在脚本中设置中文字符即可。设置方法如下: ```python import matplotlib.pyplot as plt # 设置中文字符 plt.rcParams['font.family'] = ['SimHei'] # 宋体SimHei, 黑体SimHei等 plt.rcParams['axes.unicode_minus'] = False # 解决负号'-'显示为方块的问题 # 进行绘图 plt.plot([1,2,3],[4,5,6]) plt.show() ``` 2. 使用特定字体 使用特定字体可以更好地控制字体的大小、样式、颜色等。具体操作如下: (1)首先需要下载所需字体文件,这里以“宋体”为例,将宋体字体的 .ttf 文件下载到本地,例如在 C 盘根目录下新建一个 fonts 文件夹,并将宋体字体的 .ttf 文件放在该文件夹中。 (2)在 Matplotlib 中注册该字体: ```python import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 定义所需字体的路径 font_path = 'C:/fonts/simfang.ttf' # 宋体simfang # 注册该字体 font_prop = fm.FontProperties(fname=font_path) # 进行绘图 plt.plot([1,2,3],[4,5,6]) plt.xlabel('温度', fontproperties=font_prop, fontsize=14) plt.ylabel('湿度', fontproperties=font_prop, fontsize=14) plt.show() ``` 在上述代码中,首先定义了宋体字体的路径并将其赋值给 font_path 变量;接下来使用 FontManager 对象定义了一个 FontProperties 对象,其中设置了字体文件路径和字体大小;最后在文本中使用该 FontProperties 对象进行中文字符的显示。 注意,在使用特定字体时,需要确保所选字体名字和字体文件对应,字体文件的路径也需要正确设置
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值