Series Article Directory
Chapter 1 The Chinese display of the drawing text in the common Python library matplotlib
Chapter 2 The meaning and modification method of each module in the drawing of the Python common library matplotlib
Chapter 3 Multiple subgraph drawing in the Python common library matplotlib
Article directory
foreword
When visualizing data, it is often necessary to use legends to explain the meaning of different elements in the graph. When writing a thesis, especially when writing a graduation thesis, it is necessary to display Chinese in the text in the picture, and use New Roman typeface for the numbers. However, the matplotlib library does not support Chinese display by default, so some settings are required to display Chinese when drawing legends. This article will introduce how to use the matplotlib library to draw Chinese legends.
1. What is matplotlib?
Matplotlib is a Python library for creating visual charts. It supports a variety of chart types, including line charts, scatter plots, bar charts, pie charts, 3D charts, etc. It is the most commonly used in data analysis, scientific computing and engineering applications One of the visualization tools. The Matplotlib library is widely used in data analysis, machine learning, scientific computing and other fields of Python, as well as in research, education and industrial production. It is an open source software and is available in several versions of Python.
The installation of the matplotlib library is simple
pip install matplotlib
The version of matplotlib used in this article is 3.6.2. You can enter the following command to install this version directly.
pip install matplotlib==3.6.2
2. How to use
Take the following simple code as an example to describe how to change the text in the drawing.
import numpy as np
import matplotlib.pyplot as plt
# 绘制曲线
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label=u'正弦曲线')
plt.plot(x, y2, label=u'余弦曲线')
plt.xlabel('横轴')
plt.ylabel('纵轴')
plt.title('函数')
# 添加图例
plt.legend(loc='upper right')
# 显示图像
plt.show()
The above code achieves drawing sine and cosine curves on the same graph, and the display result is as shown in the figure below. It can be
seen that if no font settings are added, the horizontal and vertical coordinates and the Chinese characters of the legend are all boxes.
1. Find the font you need
(1) Download fonts
linux
Generally, fonts such as Microsoft Yahei, Times New Roman, and New Roman are not included. We need to find it. If you have windows
a system computer by your side, you can go to the following paths to copy
font name | path |
---|---|
Microsoft Yahei | C:\Windows\Fonts\msyh.ttc |
Times New Roman | C:\Windows\Fonts\simsun.ttc |
new rome | C:\Windows\Fonts\TIMES.TTF |
If you are too lazy, you can also download the font file of the font package I uploaded.
Extraction code: z58v
(2) Place it in a suitable path
linux mint
The font files under . Generally, font files will have another layer of folders under the truetype folder before arriving at the font files.
In the case of dejavu, that's it.
So we can also create a yahei folder to place its font files
# 创建yahei文件夹
sudo mkdir /usr/share/fonts/truetype/yahei
# 拷贝字体文件到该文件夹下
sudo cp msyh.ttc /usr/share/fonts/truetype/yahei/
(3) Refresh the font cache
sudo fc-cache -f -v
(4) Confirm whether the font file has been installed
Enter the following code in the terminal, you can see the installation path of Microsoft Yahei
fc-list | grep -i yahei
Similarly, see New Rome's
fc-list | grep TIMES
View the Times New Roman
fc-list | grep SUN
(4) Delete the cache of matplotlib
This step is so important that many people forget
rm rf ~/.cache/matplotlib
2. Set the font
(1) Set the font globally
Just add the following code before the previous code.
# 设置字体
plt.rcParams['font.family'] = 'Microsoft YaHei'
The final code is as follows:
import numpy as np
import matplotlib.pyplot as plt
# 设置字体
plt.rcParams['font.family'] = 'Microsoft YaHei'
# plt.rcParams['font.family'] = 'SimSun'
# plt.rcParams['font.family'] = 'Times New Roman'
# 绘制曲线
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label=u'正弦曲线')
plt.plot(x, y2, label=u'余弦曲线')
plt.xlabel('横轴')
plt.ylabel('纵轴')
plt.title('函数')
# 添加图例
plt.legend(loc='upper right')
# 显示图像
plt.show()
Run the code and see that the drawing appears in Chinese. Comment
out this to display Times New Roman. If enabled . We found that the frame appeared again. Obviously, New Roman does not support Chinese display, only the numbers have become New Roman. For targets at different locations, set different fonts, which can be modified by the following codeplt.rcParams['font.family'] = 'Microsoft YaHei'
plt.rcParams['font.family'] = 'SimSun'
plt.rcParams['font.family'] = 'Times New Roman'
import numpy as np
import matplotlib.pyplot as plt
# 设置字体
plt.rcParams['font.family'] = 'SimSun'
plt.rcParams['font.family'] = 'Times New Roman'
# 绘制曲线
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label=u'正弦曲线')
plt.plot(x, y2, label=u'余弦曲线')
# 设置横轴字体
plt.xlabel('横轴', fontfamily='SimSun')
# 设置纵轴字体
plt.ylabel('纵轴', fontfamily='SimSun')
# 设置标题字体
plt.title('函数', fontfamily='SimSun')
# 设置刻度字体
plt.xticks(fontfamily='Times New Roman')
plt.yticks(fontfamily='Times New Roman')
# 设置图例字体
plt.legend(loc='upper right', fontsize=12, edgecolor='black', fancybox=False, framealpha=1, prop={
'family': 'SimSun'})
# 显示图像
plt.show()
final display result
(2) Set font locally ( strongly recommended )
It seems a bit cumbersome to copy or download font files for the above settings on a new machine. Now introduce the second method, directly put yourself in the same directory as the running program or script. In this way, the font follows the code, and it can be run directly in a new environment as long as matplotlib is installed.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# 指定字体
font_path = 'SIMSUN.TTC' # 这里也可以填其他字体的绝对路径,只填名称表示本程序与该字体在同一级目录下
font_prop = fm.FontProperties(fname=font_path, size=12)
en_font_path = 'TIMES.TTF' # 这里也可以填其他字体的绝对路径,只填名称表示本程序与该字体在同一级目录下
en_font_prop = fm.FontProperties(fname=en_font_path, size=12)
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label=u'正弦曲线')
plt.plot(x, y2, label=u'余弦曲线')
plt.xlabel('横轴', fontproperties=font_prop)
plt.ylabel('纵轴', fontproperties=font_prop)
plt.title('函数', fontproperties=font_prop)
plt.xticks(fontproperties=en_font_prop)
plt.yticks(fontproperties=en_font_prop)
plt.legend(loc='upper right', fontsize=12, edgecolor='black', fancybox=False, framealpha=1, prop=font_prop)
plt.show()
view display results
Summarize
This article briefly introduces how to use the matplotlib library to add Chinese font display. One is set globally, and the other is set for the current program.