This article mainly introduces how to solve the problem of Chinese garbled characters generated by matplotlib under ubuntu. As shown below
Solutions
- Prepare Chinese fonts
- matplotlib specifies the font as Chinese font
- Empty matplotlib to make the configuration take effect
Prepare Chinese fonts
- Download the Chinese ttf file, or copy it from the Windows operating system. As in bold (click to download)
- Double-click to install/ or cp to /usr/share/fonts/truetype/dejavu/
- Run the command
fc-list :lang=zh-cn
in the terminal to view the corresponding Chinese fonts配置名
. The corresponding names in bold areSimHei
.
matplotlib specifies the font as Chinese font
- Copy the Chinese font files to the fonts/ttf directory of matplotlib. The complete catalog is
/usr/local/lib/python*/dist-packages/matplotlib/mpl-data/fonts/ttf
- Modify the configuration
/usr/local/lib/python*/dist-packages/matplotlib/mpl-data/matplotlibrc
file
# 搜索font.family配置项,将其#注释去掉,并将:号后面的值改为字段对应的名字。
font.family : SimHei
# 搜索axes.unicode_minus配置项,将其#注释去掉,并将:号后面的值改为False
axes.unicode_minus : False
save and exit
Empty matplotlib to make the configuration take effect
rm ~/.cache/matplotlib -R
final renderings
The test code used in this article
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = x * 2
plt.title("一元一次函数")
plt.plot(x, y)
plt.show()