Python利用Matplotlib绘图无法显示中文字体的解决方案
生活随笔
收集整理的這篇文章主要介紹了
Python利用Matplotlib绘图无法显示中文字体的解决方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里寫目錄標題
- 問題描述
- 報錯信息
- 解決方法
- 其他解決方案
- 使用模板(內置樣式)后無法顯示中文的解決方案
問題描述
在Python利用Matplotlib繪圖的時候,無法顯示坐標軸上面的中文和標題里面的中文
import matplotlib.pyplot as plt from numpy import squaresquares = [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 pltimport matplotlib matplotlib.rc("font", family='Microsoft YaHei') from numpy import squaresquares = [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:蘋果麗中黑;
總結
以上是生活随笔為你收集整理的Python利用Matplotlib绘图无法显示中文字体的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rsync来实现文件同步
- 下一篇: 〖Python APP 自动化测试实战篇