How to make matplotlib display Chinese correctly

How to make matplotlib display Chinese correctly. Thank you .

import numpy as np 
from matplotlib import pyplot as plt 
import matplotlib

from pylab import mpl

import pymysql

matplotlib.rcParams ['font.family'] = ['HGFS1_CNKI'] # Still show white square 



plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False



districts = ['鼓楼', '建邺', '栖霞', '雨花台', '秦淮', '玄武', '江宁', '浦口', '六合', '溧水', '高淳']
nums = [3172, 1733, 1973, 1372, 2434, 2246, 3338, 1435, 849, 942, 94]

plt.bar(range(len(nums)), nums, tick_label=districts)
plt.show()

sudo cp HGFS1_CNKI.TTF /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf/

enter image description here

Answer

解决matplotlib不显示中文的方法被我找到了。
首先要引用
from matplotlib import font_manager
将支持中文的ttc字体放在本地或指定目录下
my_font = font_manager.FontProperties(fname="./NotoSerifCJK-Bold.ttc")
如果横坐标有中文
plt.xticks(range(len(districts)),districts,fontproperties=my_font)
重点就是fontproperties=my_font这句话

Leave a Reply

Your email address will not be published. Required fields are marked *