ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python: matplotlib绘图区自定义中英文字体以及部分设置

2022-03-07 15:31:47  阅读:607  来源: 互联网

标签:None plt family 自定义 Python matplotlib 字体 font


对于matplotlib绘图区总是有比较强迫症的自定义要求,对于刚刚接触Python的新手来说,各种配置起来还是比较繁琐,因此开一个帖子作为注记备忘。(Jupyter-Based)

  • 内置字体:

只能选择同款字体,用默认英文字体无法显示中文,用宋体的话中文能够显示但英文较丑。这里采用rcParams全局设置参数,也可使用font_manager.FontProperties()对象函数,参考matplotlib网页原文设置如下。

class matplotlib.font_manager.FontProperties(family=None, style=None, variant=None, weight=None, stretch=None, size=None, fname=None, math_fontfamily=None)[source]
Bases: object

A class for storing and manipulating font properties.

The font properties are the six properties described in the W3C Cascading Style Sheet, Level 1 font specification and math_fontfamily for math fonts:

family: A list of font names in decreasing order of priority. The items may include a generic font family name, either 'sans-serif' (default), 'serif', 'cursive', 'fantasy', or'monospace'. In that case, the actual font to be used will be looked up from the associated rcParam.

style: Either 'normal' (default), 'italic' or 'oblique'.

variant: Either 'normal' (default) or 'small-caps'.

stretch: A numeric value in the range 0-1000 or one of 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal' (default), 'semi-expanded', 'expanded', 'extra-expanded' or 'ultra-expanded'.

weight: A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal' (default), 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'.

size: Either an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' or an absolute font size, e.g., 10 (default).

math_fontfamily: The family of fonts used to render math text; overrides rcParams["mathtext.fontset"] (default: 'dejavusans'). Supported values are the same as the ones supported by rcParams["mathtext.fontset"] (default: 'dejavusans'): 'dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans' and 'custom'.

%matplotlib qt5 
#以互动窗口打开matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager

config = {
    "font.family":'serif', # sans-serif/serif/cursive/fantasy/monospace
    "font.size": 20, # medium/large/small
    'font.style':'normal', # normal/italic/oblique
    'font.weight':'normal', # bold
    "mathtext.fontset":'cm',# 'cm' (Computer Modern)
    "font.serif": ['cmb10'], # 'Simsun'宋体
    "axes.unicode_minus": False,# 用来正常显示负号
}
plt.rcParams.update(config)

x = np.linspace(0, 6, 50)
plt.plot(x, np.sin(x), label = r"Sine $\sin(\theta)$")
plt.title(r'Sine Function $\alpha_i \leq \beta_j$')
plt.xlabel(r'$\theta_i$')
plt.ylabel(r'$\sin\theta$')
plt.ion()
plt.show()

效果:

  • 自定义字体:

用户希望自定义字体,即分别设置中文、英文、数学公式的字体,由于这里采用字体融合的应用将中英文混合,通过导入ttf文件以满足自定义配置的要求。(好看的图片,流程比较繁琐)

可以参考结合Github-字体合并/补全工具进行配置。

%matplotlib qt5 
# iPython以互动窗口打开matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager

font_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' (Computer Modern)

x = np.linspace(0, 6, 50)
plt.plot(x, np.sin(x), label = r"正弦函数 Sine $\sin(\theta)$")
plt.title(r'中文测试 Sine Function $\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()

效果:

  • 错误排查:
  1. 互动窗口打开、内联图像窗口打开
%matplotlib qt5 # iPython以互动窗口打开matplotlib
%matplotlib inline # 以内联静态窗口绘制matplotlib
  1. 图像无法导出pdf\eps,显示Truetype font is missing table

好像更新ipython和matplotlib最新版本能够解决。如果不能解决可能只能直接plt.savefig('${File_Name}.pdf')来保存。

  1. findfont: Font family [ xxx ] not found. Falling back to DejaVu Sans.

参考此文→→ findfont: Font family [ msyh ] not found. Falling back to DejaVu Sans.

参考资料:

标签:None,plt,family,自定义,Python,matplotlib,字体,font
来源: https://www.cnblogs.com/jjmg/p/python_matplotlib_pyplot_font_setting.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有