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

如何设置Matplotlib suptitle的字体大小与颜色?

Matplotlib suptitle设置fontproperties报错的原因与解决方法

报错原因

fontproperties参数仅负责配置字体本身的属性(如字号、字体家族、字重、斜体等),它接收的是FontProperties实例,或者用于初始化该类的参数字典。而color是标题文本(Text对象)的独立样式属性,不属于字体属性范畴,把它放进fontproperties字典里,会导致FontProperties的初始化函数接收到不识别的参数,触发TypeError。

解决方法

方法1:拆分参数直接传递

将color作为独立参数传给suptitle,字体相关参数可单独传递或放在fontproperties中:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
# 直接传入所有样式参数
fig.suptitle('A title', color='r', fontsize=32)

# 或者字体参数放fontproperties,颜色单独传
font_params = {'fontsize': 32, 'family': 'serif'}
fig.suptitle('A title', color='r', fontproperties=font_params)

方法2:获取Text对象后批量设置

如果想像操作普通Text实例一样统一配置样式,可先获取suptitle返回的Text对象,再用set()方法传入完整的样式字典:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
style_dict = {'color': 'r', 'fontsize': 32, 'fontweight': 'bold'}
title_obj = fig.suptitle('A title')
title_obj.set(**style_dict)

方法3:使用FontProperties对象(纯字体属性配置)

如果仅需配置字体专属属性,可创建FontProperties实例传入,颜色仍单独传递:

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

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
font_prop = FontProperties(size=32, family='monospace', weight='bold')
fig.suptitle('A title', color='r', fontproperties=font_prop)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:22:12