Python利用Matplotlib绘图无法显示中文字体的解决方案

问题描述

在Python利用Matplotlib绘图的时候,无法显示坐标轴上面的中文和标题里面的中文

import matplotlib.pyplot as plt
from numpy import square


squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth = 3)

# 设置图表标题并给坐标轴加上标签。
ax.set_title("平方数", fontsize = 24)
ax.set_xlabel("值", fontsize = 14)
ax.set_ylabel("值的平方", fontsize = 14)

# 设置刻度标记的大小。
ax.tick_params(axis='both', labelsize =14 )


plt.show()

运行后如下界面
在这里插入图片描述

报错信息

A:\ProgramData\Anaconda3\envs\py39\lib\tkinter\__init__.py:814: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from current font. func(*args)

解决方法

在开头插入

import matplotlib
matplotlib.rc("font", family='Microsoft YaHei')

这两行代码将图片中的字体设置为了Microsoft YaHei,所以可以正常显示了

import matplotlib.pyplot as plt

import matplotlib
matplotlib.rc("font", family='Microsoft YaHei')
from numpy import square


squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth = 3)

# 设置图表标题并给坐标轴加上标签。
ax.set_title("平方数", fontsize = 24)
ax.set_xlabel("值", fontsize = 14)
ax.set_ylabel("值的平方", fontsize = 14)

# 设置刻度标记的大小。
ax.tick_params(axis='both', labelsize =14 )


plt.show()

在这里插入图片描述

其他解决方案

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei' 
# 黑体

使用模板(内置样式)后无法显示中文的解决方案

在模板代码后面加一行 plt.rcParams[‘font.sans-serif’] = ‘SimHei’

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn')
plt.rcParams['font.sans-serif'] = 'SimHei' 

fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth = 3)

在这里插入图片描述

SimSun :宋体;KaiTI:楷体;Microsoft YaHei:微软雅黑
LiSu:隶书;FangSong:仿宋;Apple LiGothic Medium:苹果丽中黑;

  • 17
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vigo*GIS_RS

来瓶可乐~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值