Operating environment:
- python3.6
- ubuntu
- matplotlib under conda3
- jupyterLab
problem:
- matplotlib draws a picture, cannot display Chinese
- When no font is added, the code and figure are shown as follows:
-
import matplotlib.pyplot as plt import random from matplotlib.font_manager import FontProperties from pylab import * # 每隔两小时range(2, 26, 2) ,数据在x轴的数据, 可迭代 x = range(2, 26, 2) y = [15, 16, 14, 17, 20, 25, 26, 24, 22, 18, 15, 10] fig = plt.figure(figsize=(20, 8), dpi=80) # (20, 8)宽20,高8,dpi设置图片清晰度, 让图片更加清晰 plt.plot(x, y) # 设置x轴, y轴的刻度 _xticks_labels = [i/2 for i in range(2, 49)] plt.xticks(_xticks_labels[: :4]) # 设置步长 plt.yticks(range(min(y), max(y)+1)) plt.title(u'中文') plt.show()
Reason (there may be other reasons):
- There are no Chinese fonts available in the linux operating system and matplotlib font library
- The matplotlib package only supports ASCII codes by default, not unicode codes
Solve the problem:
1. Find the font file library path under the matplotlib installation package under linux:
'/home/XXX/anaconda3/envs/env_keras_gpu/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf'
You can see that the font you need may not be available:
2. Download the font you need
Download path: https://github.com/dolbydu/font (GitHub)
Baidu Netdisk: Link: https://pan.baidu.com/s/1CB5gGp-A_IKJyIPFlNsMKw Extraction code: 9sef
This is the font I downloaded by myself. If you need to download other fonts, you can go to GitHub to download
3. Put the font you downloaded in the folder
'/home/XXX/anaconda3/envs/env_keras_gpu/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf'
You can see these extra fonts Micro-group Yahei-Microsoft Yahei.ttf, Hei-SimHei.ttf, Kai-Ti-STKaiti.TTF
4. After the font is downloaded, you can add fonts
Code:
import matplotlib.pyplot as plt
import random
from matplotlib.font_manager import FontProperties
from pylab import *
fname = "/home/XXX/anaconda3/envs/env_keras_gpu/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/STKaiti.TTF"
myfont = FontProperties(fname=fname)
# 每隔两小时range(2, 26, 2) ,数据在x轴的数据, 可迭代
x = range(2, 26, 2)
y = [15, 16, 14, 17, 20, 25, 26, 24, 22, 18, 15, 10]
fig = plt.figure(figsize=(20, 8), dpi=80) # (20, 8)宽20,高8,dpi设置图片清晰度, 让图片更加清晰
plt.plot(x, y)
# 设置x轴, y轴的刻度
_xticks_labels = [i/2 for i in range(2, 49)]
plt.xticks(_xticks_labels[: :4]) # 设置步长
plt.yticks(range(min(y), max(y)+1))
plt.title(u'中文',fontproperties=myfont)
plt.show()
The picture at this time is as follows:
Okay, now the problem is solved. . . .
There are other solutions, everyone can discuss and discuss
You can pay attention to the official account of my friend and me~~~ Here are some python technical information that my friend and I update from time to time! ! You can also leave a message to discuss technical issues. I hope you can support and pay attention to it. Thank you~~