How to mix Chinese and English with MatPlotLib

Background

MatPlotLib is a fantastic graphics package. But when I sometimes have to compile a dataset in Chinese. I found the problem.

There are two methods of representing non-English font with MatPlotLib.

Method 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"

      

In this method, all the text and number shown in the picture are in Chinese font.

Method 2

In other words, I will predefine the path of some Chinese font and name it when I need to use it.

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) 

      

My problem

When the string contains Chinese text and English text (for example, Chinese as a variable and it must contain several units: kg, m / s).

质量 == Mass
as.set_xlabel(u'质量' + '(kg)') ==> Want to define their font sepearetly.

      

So, I want the string to be able to blend with Chinese and English fonts together as a single unit?

Can this be achieved?

+3


source to share





All Articles