Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib Chinese Text Display

Matplotlib Chinese Text Display

Matplotlib is not particularly friendly to Chinese text display. To display Chinese in Matplotlib, we can use two methods:

Without setting the font, the default display is as follows, and Chinese characters are not displayed properly:


Matplotlib's font parameters

We can first get the list of system fonts:

Example

from

matplotlib

import

pyplot

as

plt

import

matplotlib

a

=

sorted

(

[

f.

name

for

f

in

matplotlib.

font_manager

.

fontManager

.

ttflist

]

)

for

i

in

a:

   

print

(

i

)

The output is similar to the following:


...
Heiti TC
Helvetica
Helvetica Neue
Herculanum
Hiragino Maru Gothic Pro
Hiragino Mincho ProN
Hiragino Sans
Hiragino Sans GB
Hoefler Text
...

The above code outputs all registered names in font_manager's ttflist. Find a Chinese font you like, e.g., STFangsong, Heiti TC, and then add the following code.

For Windows:


plt.rcParams['font.family'] = 'SimHei'  # 替换为你选择的字体

On Windows systems, choose SimHei or another Chinese font and set it as Matplotlib's default font.

For Linux:


plt.rcParams['font.family'] = 'WenQuanYi Micro Hei'  # 替换为你选择的字体

On Linux systems, use the fc-list command to view installed fonts, choose a Chinese font, and set it as Matplotlib's default font.

For macOS:


plt.rcParams['font.family'] = 'Heiti TC'  # 替换为你选择的字体

By setting plt.rcParams['font.family'], you tell Matplotlib to use the chosen font to render text, so that Chinese displays correctly in the chart.

This way, you can use system-supported Chinese fonts in your Matplotlib charts.

Example

import

matplotlib.

pyplot

as

plt

plt.

rcParams

[

'font.family'

]

=

'Heiti TC'

 

Replace with the font of your choice

Create data

x

=

[

1

,

2

,

3

,

4

,

5

]

y

=

[

2

,

4

,

6

,

8

,

10

]

Draw a line chart

plt.

plot

(

x

,

y

)

Add title and labels

plt.

title

(

'Line Chart Example'

)

plt.

xlabel

(

'X-axis'

)

plt.

ylabel

(

'Y-axis'

)

Display the figure

plt.

show

(

)

This way, Chinese can be displayed normally, as shown below:

Universal method for all platforms:

# -------------------------- 设置中文字体 start --------------------------
plt.rcParams['font.sans-serif'] = [
    # Windows priority
    'SimHei', 'Microsoft YaHei',
    # macOS preferred
    'PingFang SC', 'Heiti TC',
    # Linux preferred
    'WenQuanYi Micro Hei', 'DejaVu Sans'
]
# Fix the issue where negative signs display as squares
plt.rcParams['axes.unicode_minus'] = False
# -------------------------- Set Chinese font end --------------------------

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

-------------------------- Set Chinese font start --------------------------

plt.

rcParams

[

'font.sans-serif'

]

=

[

   

Windows first

   

'SimHei'

,

'Microsoft YaHei'

,

   

macOS first

   

'PingFang SC'

,

'Heiti TC'

,

   

Linux first

   

'WenQuanYi Micro Hei'

,

'DejaVu Sans'

]

Fix the issue of minus signs displaying as squares

plt.

rcParams

[

'axes.unicode_minus'

]

=

False

-------------------------- Set Chinese font end --------------------------

Generate simulated data: add some random noise on top of a sine curve

np.

random

.

seed

(

42

)

X

=

np.

linspace

(

0

,

10

,

20

)

y_true

=

np.

sin

(

X

)

                   

The true underlying pattern (which we don't know)

y_noise

=

np.

random

.

randn

(

20

)

0.3

 

Random noise

y

=

y_true + y_noise                  

The data we actually observe

plt.

scatter

(

X

,

y

,

label

=

'Observed Data (with Noise)'

,

color

=

'blue'

,

alpha

=

0.6

)

plt.

plot

(

X

,

y_true

,

label

=

'True Pattern (y=sin(x))'

,

color

=

'green'

,

linewidth

=

2

)

plt.

xlabel

(

'X'

)

plt.

ylabel

(

'y'

)

plt.

title

(

'Data and Underlying Pattern'

)

plt.

legend

(

)

plt.

grid

(

True

)

plt.

show

(

)

Our goal is to find a curve (model) that best describes the pattern reflected by these blue scatter points (the data).

The degree to which the model describes the data isfitting。


Use a font library

Matplotlib does not support Chinese by default; we can solve this with the following simple method.

Here we use Source Han Sans, an open-source font released by Adobe and Google.

Official site:https://source.typekit.com/source-han-serif/cn/

GitHub address:https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese

After opening the link, just pick one from there:

You can also download from cloud storage: https://pan.baidu.com/s/10-w1JbXZSnx3Tm6uGpPGOw, extraction code: yxqu.

You can download an OTF font, such as SourceHanSansSC-Bold.otf, and place the file in the directory of the code being executed:

Place the SourceHanSansSC-Bold.otf file in the directory of the currently executing code file:

Example

import

numpy

as

np

from

matplotlib

import

pyplot

as

plt

import

matplotlib

fname is the path to the font library you downloaded; note the path of the SourceHanSansSC-Bold.otf font

zhfont1

=

matplotlib

.

font_manager

.

FontProperties

(

fname

=

"

SourceHanSansSC-Bold.otf

"

)

x

=

np

.

arange

(

1

,

11

)

y

=

2

x

5

plt

.

title

(

"

Runoob Tutorial - Test

"

,

fontproperties

=

zhfont1

)

fontproperties sets Chinese display, fontsize sets the font size

plt

.

xlabel

(

"

x-axis

"

,

fontproperties

=

zhfont1

)

plt

.

ylabel

(

"

y-axis

"

,

fontproperties

=

zhfont1

)

plt

.

plot

(

x

,

y

)

plt

.

show

(

)

The output is shown in the following figure: