You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中设置含中文的图例标签字体?

解决Matplotlib图例中文无法显示的问题

你遇到的问题是因为图例(legend)未指定中文字体,仅给坐标轴和标题设置字体无法覆盖图例的字体配置。可以通过以下两种方式解决:

方法1:直接为图例指定字体

调用plt.legend()时,通过prop参数传入你定义好的FontProperties对象即可:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname="/path/anaconda3/envs/env_name/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf")

x = [1, 2, 3, 4]
y1 = [5, 6, 7, 8]
y2 = [8, 7, 6, 5]

plt.plot(x, y1, label='曲线1')
plt.plot(x, y2, label='曲线2')

plt.xlabel('横轴', fontproperties=font)
plt.ylabel('纵轴', fontproperties=font)
plt.title('标题', fontproperties=font)

# 给图例指定中文字体
plt.legend(prop=font)

plt.savefig('plot.png')
plt.show()

方法2:全局设置Matplotlib字体(更简洁)

通过修改Matplotlib全局配置参数,一次性让所有文本元素(图例、坐标轴、标题等)自动使用中文字体,无需逐个指定:

import matplotlib.pyplot as plt

# 全局配置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体为黑体(SimHei)
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示为方块的问题

x = [1, 2, 3, 4]
y1 = [5, 6, 7, 8]
y2 = [8, 7, 6, 5]

plt.plot(x, y1, label='曲线1')
plt.plot(x, y2, label='曲线2')

plt.xlabel('横轴')
plt.ylabel('纵轴')
plt.title('标题')

plt.legend()

plt.savefig('plot.png')
plt.show()

注意:如果你的环境中没有SimHei字体,可替换为系统已安装的其他中文字体(如'Noto Sans CJK SC'等),确保字体名称正确即可。

内容的提问来源于stack exchange,提问作者XiaoBanni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:12:43