Python3 integrated matplotlib drawing Chinese garbled solution

Problem Description

Use matplotlib to draw a picture in python, the Chinese inside will show garbled squares.

Prerequisite dependence

This is caused by the default font used by matplotlib that does not contain Chinese characters. It can be solved by adding Chinese characters to the default font.

Prerequisite: Find out which Chinese fonts are available locally

Open matplotlib fonts, default is C:\Users\用户名\.matplotlibopen fontList.json, look for Chinese font, such as simHei, song, kaietc., corresponding simplified black, Times New Roman, italics and so on.

After finding it, the corresponding namefield value is the Chinese font name we will set next, copy it down, such as imitation Song font FangSong:

 Solution:

import matplotlib
print(matplotlib.matplotlib_fname())

Will output the configuration file path, such as:

E:\python_workspace\TornadoDemo\venv\Lib\site-packages\matplotlib\mpl-data\matplotlibrc

Open the file, find #font.family这一the line, and will comment this line #removed, and thereafter add Chinese font name you want to join, such as:

Python3 + matplotlib draws a scatter plot with Chinese characters:

import matplotlib.pyplot as plt


# 定义x集合和y集合
x = [1, 2]
y = [3, 4]
# 绘制散点图,并指定标签
plt.scatter(x, y, label='标签')
# 绘制图像添加标题
plt.title('散点图')
# 绘制坐标轴
plt.xlabel('x轴')
plt.ylabel('y轴')
# 绘制图像显示
plt.show()

Guess you like

Origin blog.csdn.net/zhouzhiwengang/article/details/113065312