Colab notebook用matplotlib画图中文出现方块:
如何解决这个问题呢?
- 运行
wget -O simhei.ttf "https://www.wfonts.com/download/data/2014/06/01/simhei/chinese.simhei.ttf"
,安装中文字体,这里装得是SimHei,也就是黑体中文 - 添加以下两行代码即可
matplotlib.font_manager.fontManager.addfont('simhei.ttf')
matplotlib.rc('font', family='SimHei')
运行结果:
附示例源程序:
!pip install matplotlib!wget -O simhei.ttf "https://www.wfonts.com/download/data/2014/06/01/simhei/chinese.simhei.ttf"import matplotlib.pyplot as plt
import matplotlib
import numpy as np# # 新增字體
matplotlib.font_manager.fontManager.addfont('simhei.ttf')
matplotlib.rc('font', family='SimHei')# 定义数据
grades = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级']
rating = ['中', '良', '优']
numbers = [[5647, 1024, 2160],[18301, 2756, 4810],[34048, 4326, 7744],[47731, 5576, 10514],[44271, 3562, 9149],[53252, 3564, 13213]
]barWidth = 0.25# 设置位置
r1 = np.arange(len(numbers))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]# 绘制柱形图
plt.bar(r1, [num[0] for num in numbers], color='b', width=barWidth, edgecolor='grey', label='中')
plt.bar(r2, [num[1] for num in numbers], color='r', width=barWidth, edgecolor='grey', label='良')
plt.bar(r3, [num[2] for num in numbers], color='g', width=barWidth, edgecolor='grey', label='优')# 描述柱形图
plt.xlabel('年级', fontweight='bold')
plt.xticks([r + barWidth for r in range(len(numbers))], grades)# 创建图例
plt.legend()# 显示图表
plt.show()
参考博文:
在Colab上讓matplotlib顯示中文
Colab使用matplotlib和seaborn绘图中文乱码问题解决