Matplotlib 是 Python 中广泛利用的画图库,尤其在数据可视化范畴有着弗成调换的地位。但是,对中文用户来说,Matplotlib 默许的英文字体设置每每无法满意须要,招致中文表现为乱码或无法表现。本文将具体介绍怎样轻松处理 Matplotlib 中文表现困难,帮助你实现清楚、美不雅的图表展示。
起首,确保你的体系中安装了支撑中文的字体。在 Windows 体系中,罕见的中文字体有 SimHei(黑体)、SimSun(宋体)等。在 Linux 或 macOS 体系中,你可能须要手动安装。
接上去,我们须要在代码中设置 Matplotlib 利用中文字体。以下供给多少种设置方法:
rcParams
全局设置import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 处理坐标轴负号表现成绩
# 示例:绘制一个包含中文标题标图表
plt.title('中文标题示例')
plt.show()
FontProperties
设置import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/Library/Fonts/SimHei.ttf', size=14) # 指定字体道路跟大小
plt.title('中文标题示例', fontproperties=font)
plt.show()
为了确保字体设置掉效,可能利用以下代码检查以后的字体设置:
import matplotlib
font_set = matplotlib.mathtext.fontset()
print(font_set)
差别操纵体系(Windows/macOS/Linux)的中文字体称号跟存放道路存在差别。以下是一些罕见操纵体系的字体设置示例:
import matplotlib.font_manager as fm
# 获取体系字体道路
font_path = fm.findfont(fm.FontProperties(fname='SimHei.ttf'))
print(font_path)
import matplotlib.font_manager as fm
# 获取体系字体道路
font_path = fm.findfont(fm.FontProperties(fname='/Library/Fonts/SimHei.ttf'))
print(font_path)
经由过程以上步调,你可能在 Matplotlib 中轻松实现中文表现,让你的图表愈加清楚、美不雅。盼望本文能帮助你处理 Matplotlib 中文表现困难,晋升数据可视化后果。