您的位置:宽带测速网 > 编程知识 > Matplotlib中怎么使用自定义字体或图标

Matplotlib中怎么使用自定义字体或图标

2025-06-27 17:07来源:互联网 [ ]

要在Matplotlib中使用自定义字体,首先需要将字体文件放置在合适的位置。然后,可以通过以下步骤在Matplotlib中使用自定义字体:

    导入matplotlib库和matplotlib.font_manager模块:
import matplotlib.pyplot as pltimport matplotlib.font_manager as fm
    使用fm.FontProperties类加载自定义字体文件:
custom_font = fm.FontProperties(fname='path/to/custom/font.ttf')
    在绘图时,使用fontproperties参数指定使用自定义字体:
plt.title('Title', fontproperties=custom_font)plt.xlabel('X Label', fontproperties=custom_font)plt.ylabel('Y Label', fontproperties=custom_font)plt.show()

如果要在Matplotlib中使用自定义图标,可以使用matplotlib.markers.MarkerStyle类来创建自定义图标。以下是一个示例代码:

import matplotlib.pyplot as pltimport matplotlib.markers as markers# 创建自定义图标custom_marker = markers.MarkerStyle("o")custom_marker._transform = custom_marker.get_path().transformed(plt.gca().transData)# 绘制图形plt.scatter([1, 2, 3], [4, 5, 6], marker=custom_marker, color='blue')plt.show()

通过以上步骤,您可以在Matplotlib中使用自定义字体和图标。