一、问题
1.使用plt.bar中文后会显示为小方框:
import matplotlib.pyplot as plt
x = ["张三", "b", "c", "d"]
y = [1, 2, 4, 3]
plt.bar(x,y)
plt.show()
二、解决
准备字体文件-->更改配置文件-->清除缓存--->修改代码
1.备字体
此处,我是从Windows上copy了一份字体文件,选择一个中文字体文件,比如:宋体simsun.ttc,将它移动到Matplotlib.字体文件夹中:
~/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/
2.改配置
更改~/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc文件,在#font.sans-serif 上一行的结尾添加字体的英文名
3.删cache
rm -rf ~/.cache/matplotlib
rm -rf ~/.matplotlib
4.改代码
在刚刚的py文件加入plt.rcParams['font.sans-serif'] = ['simsun']
如下:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['simsun']
x = ["张三", "b", "c", "d"]
y = [1, 2, 4, 3]
plt.bar(x,y)
plt.show()
重新运行显示中文成功:
参考: