1、Matplotlib 常用函数
- Matplotlib 默认是有边框的,如果取消:
1 | # 取消边框 |
- 加网格
1 | # 添加 y 轴网格 |

如何出现上图虽然没有刻度但是有网格的效果呢?
目前只会一种做法,比较麻烦,但是可以解决问题:
1
2
3
4
5
6
7
8 x_labels = ["0°","","","30°","","","60°","","","90°","","","60°","","","30°","","","0°"]
y_labels = ["","7","","8","","9","","10","","11","","12","","13","","14","","15"]
# # 添加网格
plt.grid(linestyle='--')
plt.yticks(np.arange(6.5,15.5,0.5), labels=y_labels, fontproperties='Times New Roman',size=16)
plt.xticks(range(0,15062,836),labels=x_labels,fontproperties='Times New Roman',size=16)
2、Matplotlib无法显示中文问题
- 方法一:在每个目录单独申明所使用的字体,注意 Win 和 Mac 是有区别的,因为 Win 的一些字体 Mac 没有。
- 优点:简单,直接加上下述代码即可
- 缺点:每个都得加,而且系统里没有的字体无法指定
1 | # MAC |
- 方法二:全局申明,将需要的字体保存到 matplotlib 的字体库中,然后更新配置文件
- 缺点:复杂
- 优点:一劳永逸,可以添加系统里没有的字体
针对MacOS系统:
Step1. 在终端进入python3环境,查看matplotlib字体路径:
1 | import matplotlib |
找到自己的matplotlib字体文件路径:
比如/Users/gavin/opt/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc
1
Step2. 下载SimHei.ttf
字体
[Times New Roman.tff 下载地址2](https://gavin-pic-1302578220.cos.ap-beijing.myqcloud.com/times new roman.ttf)
Step3. 将下载好的SimHei.ttf字体移动到第一步查询到的字体目录./fonts/ttf/下:
1 | mv ~/Downloads/SimHei.ttf ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/SimHei.ttf |
Step4. 打开终端,进入python环境,清理matplotlib缓冲目录:
1 | import matplotlib |
Step5. 修改原始文件:
打开第一步找到的字体路径:/Users/gavin/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
进行修改:
访达跳转路径快捷键:
command + shift + G
跳转目录快捷键:
command + F
查找指定内容
如font.family
, font.sans-serif
,axes.unicode_minus
.
1 | #去掉前面的# |
Step6. 重启电脑,测试是否成功
1 | import matplotlib.pyplot as plt |