背景
MatPlotLib是一个非常棒的图形包。但有时我需要用中文绘制数据集。我发现了一些问题。
用MatPlotLib表示非英语字体有两种方法.
方法1
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # YaHei is one common Chinese font
mpl.rcParams['axes.unicode_minus'] = False # Repair the bug of representing '-'as "square"根据这种方法,图中显示的所有文本和数字都是中文字体。
方法2
不同的是,我预先定义了一些中文字体的路径,并在需要使用时调用它。
from matplotlib.font_manager import FontProperties
chinese = FontProperties(fname=r'/Library/Fonts/Microsoft/SimHei.ttf', size=20)
ax = plt.gca()
ax.set_title(u'能量随时间的变化', fontproperties=chinese) 我的问题
当字符串同时包含中文文本和英文文本时(例如,中文作为变量,它应该带有一些单位: kg,m/s.)
质量 == Mass
as.set_xlabel(u'质量' + '(kg)') ==> Want to define their font sepearetly.那么,我想把字符串和中、英文字体混为一谈吗?
是否有可能做到这一点?
发布于 2018-12-16 06:23:33
好的,我已经对方法1做了一些试验。结果支持了我的猜测。这是我的密码。
import matplotlib
mpl.use('pgf') # stwich backend to pgf
import matplotlib.pyplot as plt
plt.rcParams.update({
"text.usetex": True,# use default xelatex
"pgf.rcfonts": False,# turn off default matplotlib fonts properties
"pgf.preamble": [
r'\usepackage{fontspec}',
r'\setmainfont{Times New Roman}',# EN fonts Romans
r'\usepackage{xeCJK}',# import xeCJK
r'\setCJKmainfont{SimSun}',# set CJK fonts as SimSun
r'\xeCJKsetup{CJKecglue=}',# turn off one space between CJK and EN fonts
]
})
plt.rcParams['savefig.dpi']=300
plt.figure(figsize=(4.5, 2.5))
plt.plot(range(5))
plt.text(2.5, 2., "\CJKfontspec{SimHei}{黑体标注}")# Annotation by SimHei
plt.xlabel("宋体坐标标签(units)")# CJK&EN fonts mixed
plt.tight_layout(.5)
plt.savefig('examples.png')发布于 2020-07-11 06:55:39
通常,我们需要“时代新罗马”的英文字体和"SimSun“的中文字体。"font.family“定义了全局字体。对于单位,我们可以使用数学公式。然而,没有“时代新罗马”字体的公式。所以我用"stix“来代替”时代新罗马人“。
import matplotlib.pyplot as plt
rc = {"font.family" : "Times New Roman",
"mathtext.fontset" : "stix",
}
plt.rcParams.update(rc)enter image description here
fig,ax = plt.subplots(dpi = 300)
ax.set_xlabel(r'密度$\mathrm{kg/m}^3$',fontname = 'SimSun',fontsize = 20)
ax.text(0.2,0.8,r'宋体 $\mathrm{Times New Roman}$(正体)',fontname = 'SimSun',fontsize = 20)
ax.text(0.2,0.6,r'宋体 $Times New Roman$(斜体)',fontname = 'SimSun',fontsize = 20)
ax.text(0.2,0.4,r'$\mathrm{m^3}\ m^3$',fontsize = 30)
fig.tight_layout()
plt.show()希望它能帮到你!
https://stackoverflow.com/questions/44008032
复制相似问题