Python: matplotlib绘图区自定义中英文字体以及部分设置
对于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: objectA 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()
效果:
- 错误排查:
- 互动窗口打开、内联图像窗口打开
%matplotlib qt5 # iPython以互动窗口打开matplotlib
%matplotlib inline # 以内联静态窗口绘制matplotlib
- 图像无法导出pdf\eps,显示
Truetype font is missing table
好像更新ipython和matplotlib最新版本能够解决。如果不能解决可能只能直接plt.savefig('${File_Name}.pdf')
来保存。
findfont: Font family [ xxx ] not found. Falling back to DejaVu Sans.
参考此文→→ findfont: Font family [ msyh ] not found. Falling back to DejaVu Sans.
参考资料:
- [1] matplotlib-中文字体设置
- [2] matplotlib-入门--font
- [3] jupyter-lab用matplotlib画图实现交互展示
- [4] 魔兽世界字体合并/补全工具 1.0.0
- [5] python matplotlib 画图小技巧: 自定义字体
- [6] 用Python的matplotlib画图,怎么保证xlabel中中文用宋体,英文用新罗马?
- [7] 中文变小框框?深入剖析matplotlib的字体逻辑
- [8] python matplotlib 中文显示参数设置
- [9] 【python学习】-matplotlib图形设置(线宽、标签、颜色、图框、线类型、图例大小位置、图框大小及像素等)
- [10] 【Python基础】matplotlib字体设置看这一篇就够了
- [11] Matplotlib 3.5.1 documentation官方文档