matplotlib添加字体、字体格式自定义

本文详细介绍了如何在matplotlib中添加和自定义字体,包括全局字体设置、使用`fontproperties`、`prop`和`fontdict`参数的方法,以及在不同元素(如标题、坐标轴标签、图例等)上的应用,帮助你实现更美观的图表排版。
该文章已生成可运行项目,

1.向matplotlib添加字体

比如添加Times New Roman字体,参照此篇博客

2.画图时自定义字体格式

from matplotlib import pyplot as plt

fig, ax = plt.subplots()

2.0 修改全局字体

对于Axes对象设置刻度字体很麻烦(先设定位置再设定文字)。有一条捷径就是先设置全局字体为预期的刻度字体,然后再设置别的地方的字体,如较为容易设置的标题字体、坐标轴标签字体、图例字体等。

plt.rc('font',family='Times New Roman', size=15)

2.1 用fontproperties参数的一类方法

这一类方法包括plt.xlabel, plt.ylabel, ax.set_xlabel, ax.set_ylabel, plt.xticks, plt.yticks, plt.title, ax.set_title
首先实例化一个FontProperties类,然后在调用函数时传给fontproperties

from matplotlib import font_manager as fm

font_properties = fm.FontProperties(**kwargs)
plt.xlabel('xlabel', fontproperties=font_properties)
plt.yticklabels(fontproperties=font_properties)

其中可以指定的关键字参数有如下这些在这里插入图片描述

2.2 用prop参数的一类方法

这类方法主要是绘制图例函数plt.legend, ax.legend
首先定义一个fontdict,然后在调用函数时把fontdict传给prop参数
其中fontdict的可选键名与FontProperties的可选参数名一样

fontdict = {'family':'Times New Roman', 'size':19}
plt.legend(loc='best',prop=fontdict)

2.3 用fontdict参数的一类方法

其中包括plt.xlabel, plt.ylabel,plt.text ax.text ax.set_xticklabels ax.set_yticklabels等。
(没想到吧,plt设定ticklabelAxes对象设定ticklabels方法竟然不一样!!)
也是定义一个fontdict,只不过这次传给的是fontdict参数。

font_dict = {'math_fontfamily':'cm', 'size':19}
plt.text(r'$S = \pi r^2$',fontdict=font_dict)
xticks = ax.get_xticks()
ax.set_xticks(xticks)
ax.set_xticklabels(xticks, fontdict=font_dict)

2.4 汇总

方法位置参数名传入的参数类型
plt.xlabel, plt.ylabel, ax.set_xlabel, ax.set_ylabel, plt.xticks, plt.yticks,plt.title,ax.set_titlefontpropertiesFontProperties实例
plt.legend, ax.legendpropfontdict字典
plt.xlabel, plt.ylabel,plt.text, ax.text, ax.set_xticklabels, ax.set_yticklabelsfontdictfontdict字典
本文章已经生成可运行项目
<think> 根据用户的问题,他想要了解如何为matplotlib永久配置自定义字体。结合之前的引用内容,特别是引用[1]和引用[3]提到的内容,我们可以提供以下解决方案: ### 永久配置自定义字体的步骤 #### 1. **查找Matplotlib字体目录** 首先,我们需要找到Matplotlib字体目录,将自定义字体文件放入该目录。 ```python import matplotlib as mpl print(mpl.get_cachedir()) # 这会打印缓存目录,但字体目录通常在mpl.get_data_path()下的fonts目录 ``` 更准确的方式是获取数据路径: ```python import matplotlib print(matplotlib.matplotlib_fname()) # 显示配置文件路径,其所在目录的fonts子目录即为字体目录 ``` 通常,字体目录位于: - Linux: `/usr/local/lib/python3.x/site-packages/matplotlib/mpl-data/fonts/ttf/` - Windows: `C:\Python3x\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\` - Mac: `/Library/Frameworks/Python.framework/Versions/3.x/lib/python3.x/site-packages/matplotlib/mpl-data/fonts/ttf/` 或者使用代码获取: ```python import matplotlib as mpl print(mpl.get_data_path() + '/fonts/ttf/') ``` #### 2. **将字体文件复制到字体目录** 将你的自定义字体文件(如`MyCustomFont.ttf`)复制到上述路径中。确保字体文件是TrueType格式(.ttf)或OpenType格式(.otf)。 #### 3. **清除Matplotlib字体缓存** 删除Matplotlib字体缓存文件,通常位于缓存目录(`mpl.get_cachedir()`返回的路径)下的`fontlist-*.json`文件。例如: ```bash rm -rf ~/.cache/matplotlib/fontlist-*.json ``` 或者在代码中清除: ```python from matplotlib.font_manager import _rebuild _rebuild() # 重建字体缓存 ``` #### 4. **修改Matplotlib配置文件(可选但推荐)** 编辑Matplotlib的配置文件`matplotlibrc`,设置默认字体: ```python import matplotlib print(matplotlib.matplotlib_fname()) # 显示配置文件路径,打开该文件 ``` 在文件中修改以下行: ``` font.family : sans-serif font.sans-serif : MyCustomFont, DejaVu Sans, Bitstream Vera Sans, ... # 将你的字体名称放在最前面 ``` 注意:字体名称是文件名去掉扩展名(例如,文件`SourceHanSansSC-Regular.otf`的字体名称为`Source Han Sans SC`)。 #### 5. **验证配置** 重启Python环境,运行测试代码: ```python import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'sans-serif' # 使用sans-serif字体族 plt.rcParams['font.sans-serif'] = ['MyCustomFont'] # 指定你的自定义字体 plt.plot([1, 2, 3], [4, 5, 6]) plt.title('测试中文:你好世界!') plt.show() ``` ### 注意事项 - **字体名称的获取**:可以使用`FontProperties`查看字体名称: ```python from matplotlib.font_manager import FontProperties font = FontProperties(fname='path/to/MyCustomFont.ttf') print(font.get_name()) ``` - **系统权限**:复制字体Matplotlib系统目录可能需要管理员权限。 - **虚拟环境**:在虚拟环境中,Matplotlib的数据路径可能位于虚拟环境目录内。 ### 引用说明 上述方法参考了Matplotlib官方文档中关于字体管理的部分[^1],以及永久配置字体的实践指南[^3]。 §§相关问题§§ 1. 如何解决Matplotlib中文字体显示为方框的问题? 2. 如何在Matplotlib中同时使用中文和LaTeX数学公式? 3. 如何为Seaborn图设置自定义字体? </think>要为 Matplotlib **永久配置自定义字体**,请按照以下步骤操作: ### 📌 永久配置步骤 #### 1. **查找字体目录** ```python import matplotlib as mpl print(mpl.get_data_path() + "/fonts/ttf/") # 输出:/usr/local/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/ ``` #### 2. **复制字体文件** 将你的自定义字体文件(如 `MyFont.ttf`)复制到上述目录: ```bash # Linux/macOS cp MyFont.ttf /usr/local/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/ # Windows copy MyFont.ttf "C:\Python39\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\" ``` #### 3. **修改配置文件** 找到 Matplotlib 配置文件路径: ```python print(mpl.matplotlib_fname()) # 输出:/usr/local/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc ``` 编辑该文件,添加: ```ini font.family : sans-serif font.sans-serif : MyFont, DejaVu Sans, Arial # 将MyFont放在首位 ``` #### 4. **清除并重建字体缓存** ```python import matplotlib.font_manager as fm fm._rebuild() # 重建字体缓存 ``` #### 5. **验证配置** ```python import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'sans-serif' # 使用配置文件设置 plt.title("永久字体测试: 你好世界!") # 应显示中文 plt.show() ``` ### 🔍 关键原理 1. **字体目录优先级** Matplotlib 优先加载 `mpl-data/fonts/` 中的字体,通过修改此目录实现永久生效 $$ \text{字体路径} = \Omega_{\text{matplotlib}} \cup \Omega_{\text{system}}} $$ 其中 $\Omega_{\text{matplotlib}}$ 具有最高优先级[^1] 2. **缓存机制** 字体列表缓存于 `~/.cache/matplotlib/fontlist-*.json`,修改后需调用 `_rebuild()` 更新 ### ⚠️ 注意事项 1. **字体名称验证** 使用代码确认字体注册名称: ```python [f.name for f in fm.fontManager.ttflist if 'MyFont' in f.fname] ``` 2. **多平台兼容** 在配置文件中使用通用字体族声明: ```ini # 跨平台配置示例 font.sans-serif : MyFont, Source Han Sans SC, Microsoft YaHei, AppleGothic ``` 3. **版本升级处理** Matplotlib 升级后需重新复制字体文件到新版本的 `mpl-data/fonts/` 目录 ### 🌰 实际案例(Windows平台) ```powershell # 将微软雅黑设为默认 copy C:\Windows\Fonts\msyh.ttc "C:\Python39\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\" ``` 编辑 `matplotlibrc`: ```ini font.sans-serif : Microsoft YaHei, DejaVu Sans, Arial ``` > **提示**:永久配置后,所有项目无需额外代码即可使用自定义字体[^3]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值