:Detailed explanation of Matplotlib Chinese character display problem-empirical point of view免费ppt模版下载-道格办公

Detailed explanation of Matplotlib Chinese character display problem

There are many ways to solve the Chinese character display problem in Matplotlib. The following are several commonly used solutions: 1. Use the built-in Chinese fonts in the system: Matplotlib will use the default fonts for drawing, but the default fonts

When drawing with matplotlib, if Chinese is used in the drawing process, the font will appear by default Warning, Chinese characters are displayed as boxes or garbled characters, we will introduce several solutions here.


02

Directory:

  • 1. Chinese font display problem

  • 2. Several solutions

    • 2.1. Set the global font in the drawing code

    • 2.2. Set local font in drawing code

    • 2.3. Modify the default configuration font of native characters

    • 2.4. Automatically distinguish the system and select the font

  • 3. Other

    • 3.1.platform module

    • 3.2. Common Chinese font file names

1. Chinese font display problem

import matplotlib.pyplot as plt
import< /span> numpy as np

# Data for plotting
t = np.arange(-1.0, < span >1.0
, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='Time (s)', ylabel ='voltage (mV)',
title='Simple title')

plt.show()

Chinese garbled characters
C:UsersGdcanaconda3libsite-packagesmatplotlib ackends ackend_agg.py:238: RuntimeWarning : Glyph 31616 missing from current font.
font.set_text(s, 0.0, flags=flags)
...

We can see that "missing from current font" is prompted in the warning message. The literal translation is "missing (Chinese characters) in the current font". Contains Chinese characters.

For this kind of problem, the core is to set the font parameters when drawing pictures to include all the characters that need to be used.

2. Several solutions

We are solving Chinese character display When the problem arises, there are two types of solutions and multiple ways: Option 1, set the global character display font in the drawing code; Option 2, set the local font in the drawing code; Option 3, modify the font of the default configuration of the local characters.

2.1. Set global font in drawing code

rcParams modify the corresponding font of font.sans-serif or font.family

# The following code sets the font to SimHei (black body) globally to solve the problem of displaying Chinese [Windows]< br># set font.sans-serif or font.family can be
plt.rcParams['font.sans-serif'] = [' SimHei']
# plt.rcParams['font.family']=['SimHei']
# Solve the negative of the negative coordinate axis under the Chinese font Number display problem
plt.rcParams['axes.unicode_minus'] = False

BecausemacThe computer does not have SimHei (black body) font by default, you can download and install this font Or modify it to a font that comes with the system such as Arial Unicode MS, as follows:

# The following code sets the font to Arial Unicode MS globally to solve the problem of displaying Chinese [mac]
# set font.sans-serif or font.family can be
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# plt.rcParams['font.family']=['Arial Unicode MS']
# Solve the coordinate axis of the Chinese font The negative sign of the negative number shows the problem
plt.rcParams['axes.unicode_minus'] = False

rc method is basically equivalent to setting rcParams

# Set the font dictionary to SimSun (Song typeface), size 12 (default 10)
font = {'family' : 'SimSun',
'size' : '12'}
# Set font
plt.rc('font', **font)
# Solve the problem of negative coordinate axis under Chinese font Negative sign shows problem
plt.rc('axes', unicode_minus=False)

!! For example: rc('lines', linewidth=2, color=' r')Equivalent to the following:

rcParams['lines.linewidth'] = 2
rcParams['lines.color'] = < span >'r'

2.2. Set local font in drawing code

FontProperties object, in this case there is no need to deal with the negative sign

import matplotlib.pyplot as plt
import< /span> numpy as np
# Import matplotlib font management FontProperties
from matplotlib.font_manager import FontProperties

# Set the Chinese font we need to use (font file address)
my_font = FontProperties(fname=r'c:windowsfontsSimHei.ttf'< /span>, size=12)
# Data for plotting
t = np.arange(-1.0, 1.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)< br>
plt.plot(t, s)

# Set x-axis name font
plt.xlabel('time (s)', fontproperties=my_font)
plt.ylabel('voltage (mV)')
# Set title font
plt.title(< span >'Simple Title'
, fontproperties=my_font)

plt.show()
FontProperties object

Directly set the fontproperties parameter, in this case no additional negative processing is required No. Question

import matplotlib.pyplot as plt
import< /span> numpy as np

# Data for plotting
t = np.arange(-1.0, < span >1.0
, 0.01)
s = 1 + np.sin(2 * np.pi * t)

plt.plot(t, s)

# Set x-axis name font bold SimHei
plt.xlabel('time (s) ', fontproperties='SimHei')
plt.ylabel('voltage (mV)')
# Set title font Microsoft YaHei
plt.title('Simple Title', fontproperties='Microsoft YaHei')

plt .show()
fontproperties parameter

2.3. Modify the default configuration font of local characters

In addition to the above font settings in the code, we can also directly modify the default configuration font of the local characters, but in this case the code is only applicable to the local machine.

In [1]: # View configuration address
.. .: import matplotlib
...: print(matplotlib.matplotlib_fname())
C:UsersGdcanaconda3libsite-packagesmatplotlibmpl-datamatplotlibrc

New in#font.sans-serif Add fonts that support Chinese characters, such as: SimSun (宋体), you can also modify it directly#font.family: SimSun

!! #font.family: sans-serif#font.sans-serif: SimSun,

Considering the display problem of negative signs under Chinese fonts, synchronization needs to be modified#axes.unicode_minus: False

Change True to False

2.4. Automatically distinguish the system and select font [convenient]

The core is the following code:

(referenceplatform module to obtain the current system mac or windows, and then automatically select the corresponding Chinese font)

# Set the corresponding Chinese fonts according to different operating systems (Apple system and Windows system)< /span>system_font = {'Darwin': 'Arial Unicode MS', 'Windows': 'SimHei' }plt.rcParams['font.family'] = [system_font. get(platform.system())]
 import matplotlib.pyplot as plt
import numpy as np
import platform

# Set the corresponding Chinese fonts according to different operating systems (Apple system and Windows system)
system_font = {'Darwin': 'Arial Unicode MS', 'Windows': 'SimHei'}
plt.rcParams['font.family'] = [system_font.get(platform.system())]
# Solve the problem of displaying the negative sign of the negative coordinate axis in Chinese fonts< /span>
plt.rcParams['axes.unicode_minus'] = False

# Data for plotting< br>t = np.arange(-1.0, 1.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='simple title' )

plt.show()
Chinese character display

3. Others

Here we briefly introduce the module for obtaining information about the operating systemplatform and common Chinese fonts The file name information is convenient for everyone to understand!

3.1.platform module

platform module provides us with many methods to get information about the operating system.

!! Reference documentation: https://docs.python.org/3/library/platform.html

In [1]: import platform

In [2]: platform.system()
Out[2]: 'Windows'

In [3]: platform. platform()
Out[3]: 'Windows-10-10.0.18362-SP0'

In [4]: platform.version()
Out[4]: '10.0.18362'

In [5]: platform.architecture()
Out[5]: ('64bit' , 'WindowsPE')

In [6]: platform.machine()
Out[6]: 'AMD64'

In [7]: platform.node()
Out[7]: 'Gdc-PC'

In [8]: platform.processor()
Out[8]: 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel'

In [9]: platform.uname()
Out[9]: uname_result(system='Windows', node='Gdc-PC', release='10', version=< span >'10.0.18362', machine='AMD64', processor='Intel64 Family 6 Model 94 Stepping 3, GenuineIntel')
< /code>

3.2. Common Chinese font file names

< table>Chinese fontfont file name宋体SimSun黑体SimHei Microsoft YaHeiMicrosoft YaHeiMicrosoft ZhengheiMicrosoft JhengHeiNew Song StyleNSimSunNew Fine StylePMingLiU精明体MingLiUStandard italicsDFKai-SB< tr >Imitate SongFangSongItalian KaiTiOfficial scriptLiSuYouyuanYouYuanChinese Fine BlackSTXiheiChinese KaitiSTKaiti中文宋体 STSongChinese SongSTZhongsongChinese Imitation SongSTFangsongFounder Shu TiFZShuTiFounder Yao Ti< td >FZYaotiChinese Colorful CloudsSTCaiyunChinese AmberSTHupo Chinese LishuSTLitiChinese XingkaiSTXingkaiChinese New WeiSTXinwei




Previous recommendations

    < li >

    How Pandas handles dictionaries and json data

  • The 5th Anniversary of the Glory of Kings, Let's Get You Started with Basic Operations of Python Crawlers (102 Heroes + 326 Skins).



< span > Silently pay attention to Caige

Then surprise everyone

You can call me brother


I knew you were watching!

Articles are uploaded by users and are for non-commercial browsing only. Posted by: Lomu, please indicate the source: https://www.daogebangong.com/en/articles/detail/Detailed%20explanation%20of%20Matplotlib%20Chinese%20character%20display%20problem.html

Like (810)
Reward 支付宝扫一扫 支付宝扫一扫
single-end

Related Suggestion