对于matplotlib绘图区总是有比较强迫症的自定义要求,对于刚刚接触Python的新手来说,各种配置起来还是比较繁琐,因此开一个帖子作为注记备忘。(Jupyter-Based)
只能选择同款字体,用默认英文字体无法显示中文,用宋体的话中文能够显示但英文较丑。这里采用rcParams全局设置参数,也可使用font_manager.FontProperties()对象函数,参考matplotlib网页原文设置如下。
classmatplotlib.font_manager.FontProperties(family=None,style=None,variant=None,weight=None,stretch=None,size=None,fname=None,math_fontfamily=None)[source]Bases:object
Aclassforstoringandmanipulatingfontproperties.
ThefontpropertiesarethesixpropertiesdescribedintheW3CCascadingStyleSheet,Level1fontspecificationandmath_fontfamilyformathfonts:
family:Alistoffontnamesindecreasingorderofpriority.Theitemsmayincludeagenericfontfamilyname,either'sans-serif'(default),'serif','cursive','fantasy',or'monospace'.Inthatcase,theactualfonttobeusedwillbelookedupfromtheassociatedrcParam.
style:Either'normal'(default),'italic'or'oblique'.
variant:Either'normal'(default)or'small-caps'.
stretch:Anumericvalueintherange0-1000oroneof'ultra-condensed','extra-condensed','condensed','semi-condensed','normal'(default),'semi-expanded','expanded','extra-expanded'or'ultra-expanded'.
weight:Anumericvalueintherange0-1000oroneof'ultralight','light','normal'(default),'regular','book','medium','roman','semibold','demibold','demi','bold','heavy','extrabold','black'.
size:Eitheranrelativevalueof'xx-small','x-small','small','medium','large','x-large','xx-large'oranabsolutefontsize,e.g.,10(default).
math_fontfamily:Thefamilyoffontsusedtorendermathtext;overridesrcParams["mathtext.fontset"](default:'dejavusans').SupportedvaluesarethesameastheonessupportedbyrcParams["mathtext.fontset"](default:'dejavusans'):'dejavusans','dejavuserif','cm','stix','stixsans'and'custom'.
用户希望自定义字体,即分别设置中文、英文、数学公式的字体,由于这里采用字体融合的应用将中英文混合,通过导入ttf文件以满足自定义配置的要求。(好看的图片,流程比较繁琐)
%matplotlibqt5#iPython以互动窗口打开matplotlibimportnumpyasnpimportmatplotlib.pyplotaspltfrommatplotlibimportfont_managerfont_path='C:\\Users\\${User_Name}\\AppData\\Local\\Microsoft\\Windows\\Fonts\\${Font_Name}.ttf'#此处改为自己字体的路径font_manager.fontManager.addfont(font_path)prop=font_manager.FontProperties(fname=font_path)plt.rcParams['font.family']=prop.get_name()plt.rcParams['mathtext.fontset']='cm'#'cm'(ComputerModern)x=np.linspace(0,6,50)plt.plot(x,np.sin(x),label=r"正弦函数Sine$\sin(\theta)$")plt.title(r'中文测试SineFunction$\alpha_i\leq\beta_j$')plt.xlabel(r'$\theta_i$')plt.ylabel(r'$\sin\theta$')plt.legend(fontsize='small',borderpad=1.5,labelspacing=0.2)plt.ion()#plt.savefig('sin.pdf')plt.show()效果:
%matplotlibqt5#iPython以互动窗口打开matplotlib%matplotlibinline#以内联静态窗口绘制matplotlib好像更新ipython和matplotlib最新版本能够解决。如果不能解决可能只能直接plt.savefig('${File_Name}.pdf')来保存。