Colab matplotlib画图如何显示中文字体【图例坐标轴均可显示中文】

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绘图中文乱码问题解决

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值