Python matplotlib修改默認(rèn)字體的操作
matplotlib庫作為Python常用的數(shù)據(jù)可視化庫,默認(rèn)字體居然不支持中文字體,必須得吐槽一下~
閑言少敘,開始正文
方法1:在plot中指定prop參數(shù)
使用matplotlib.font_manager下的FontProperties加載中文字體
調(diào)用函數(shù)時(shí)通過prop屬性指定中文字體
import matplotlib.pyplot as pltimport matplotlib.font_manager as fmx_data = [’2011’, ’2012’, ’2013’, ’2014’, ’2015’, ’2016’, ’2017’]# 定義2個(gè)列表分別作為兩條折線的Y軸數(shù)據(jù)y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000]y_data2 = [52000, 54200, 51500,58300, 56800, 59500, 62700]# 指定折線的顏色、寬度、線形ln1, = plt.plot(x_data, y_data, color=’red’, linewidth=2.0,linestyle=’--’, label=’A書年銷量’)ln2, = plt.plot(x_data, y_data2, color=’blue’, linewidth=2.0,linestyle=’-.’, label=’B書年銷量’)# 使用my_font存出一個(gè)加載的中文字體my_font = fm.FontProperties(fname=’C:WindowsFontsYaHei.Consolas.1.12.ttf’)# 賒著prop參數(shù)未該字體plt.legend(loc=’best’, prop=my_font)plt.show()var foo = ’bar’;
方法2:修改matplotlib默認(rèn)字體
1、使用交互行獲取matplotlib配置文件的保存位置
>>>import matplotlib>>>matplotlib.matplotlib_fname()’G:Anaconda3envsPyProjectslibsite-packagesmatplotlibmpl-datamatplotlibrc’
2、打開文件,找到如下行
# font.family : sans-serif
3、修改字體為系統(tǒng)中能夠加載中文的字體(這里我用的是SimHei,即黑體)
font.family : SimHei
當(dāng)然用Yahei Consolas Hybrid也是可以的(需要自己安裝),但是Microsoft Yahei和msyh都試過了,會(huì)報(bào)錯(cuò),具體原因有待考證~
補(bǔ)充知識(shí):修改 matplotlib 的默認(rèn)配置添加雅黑字體
根據(jù)anaconda安裝路徑找到配置文件
E:softwareanaconda3Libsite-packagesmatplotlibmpl-datamatplotlibrc
打開, 找到 font.sans-serif 刪掉注釋,添加即可
重新啟動(dòng) jupyter notebook即可
在新開啟的文件中輸入,就可以正常顯示漢字
import matplotlib as mplmpl.rcParams[’font.serif’] = [’SimHei’]
以上這篇Python matplotlib修改默認(rèn)字體的操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python實(shí)現(xiàn)迪杰斯特拉算法過程解析2. Python如何進(jìn)行時(shí)間處理3. 詳解Python模塊化編程與裝飾器4. python使用ctypes庫調(diào)用DLL動(dòng)態(tài)鏈接庫5. Python中l(wèi)ogger日志模塊詳解6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式8. python裝飾器三種裝飾模式的簡(jiǎn)單分析9. python web框架的總結(jié)10. Python 日期與時(shí)間轉(zhuǎn)換的方法
