如何清除pandas绘制的子图箱线图的默认suptitle

4 投票
3 回答
3796 浏览
提问于 2025-04-18 18:05

在下面这个例子中,我想为四个不同的“功率”水平绘制“排放量”与“电压”的箱线图,每个功率水平占用一个子图。

fig = plt.figure(figsize=(16,9))
i = 0
for Power in [10, 20, 40, 60]:
    i = i+1
    ax = fig.add_subplot(2,2,i)
    subdf = df[df.Power==Power]
    bp = subdf.boxplot(column='Emission', by='Voltage', ax=ax)
fig.suptitle('My Own Title')

问题是,

fig.suptitle('My Own Title')

这个命令没有去掉默认的“按电压分组”的副标题。我漏掉了什么吗?还是说这是个bug?

谢谢。

3 个回答

0

在有人给出更好的答案之前,这里有个小技巧,假设新标题比旧标题长。

fig.suptitle('My Own Title',backgroundcolor='white', color='black')

这个方法基本上是把旧标题隐藏起来,而不是直接删除它。

5

你也可以不需要先手动创建一个图形就能做到这一点:

ax = df.boxplot(by=["some_column"])
ax.get_figure().suptitle("")
5

这些是通过 suptitle() 函数生成的,超级标题是 fig 对象的子元素(没错,suptitle() 被调用了4次,每个子图都调用了一次)。

要解决这个问题:

df = pd.DataFrame({'Emission': np.random.random(12),
                   'Voltage': np.random.random(12),
                   'Power': np.repeat([10,20,40,60],3)})
fig = plt.figure(figsize=(16,9))
i = 0
for Power in [10, 20, 40, 60]:
    i = i+1
    ax = fig.add_subplot(2,2,i)
    subdf = df[df.Power==Power]
    bp = subdf.boxplot(column='Emission', by='Voltage', ax=ax)
fig.texts = [] #flush the old super titles
plt.suptitle('Some title')

enter image description here

撰写回答