在使用Maltab画图时,subplot是非常常用的画图指令,它可以让我们将多个图像同时显示在一个figure中。但是,当我们想为这个figure添加一个总的标题时,则显得有点难搞。

Matlab为大家提供了suptitle和sgtitle等指令来实现为一个多subplots的figure添加一个总标题。suptitle和sgtitle在使用上用法相似,但功能上有较大区别。

suptitle及其用法

从help系统上可以看到,suptitle其实就是个普通的function,它的输入参数仅仅为一个字符串,所以在效果上非常非常的局限。
在这里插入图片描述

function hout=suptitle(str)
%SUPTITLE puts a title above all subplots.
%
%	SUPTITLE('text') adds text to the top of the figure
%	above all subplots (a "super title"). Use this function
%	after all subplot commands.
%
%   SUPTITLE is a helper function for yeastdemo.
%   Copyright 2003-2014 The MathWorks, Inc.
% Warning: If the figure or axis units are non-default, this
% function will temporarily change the units.
...

使用suptitle生成figure的总标题时,需要将suptitle语句放在所有subplot的最后,示例如下:

subplot(2,2,1)
x = linspace(0,10);
y1 = sin(x);
plot(x,y1)
title('Subplot 1: sin(x)')
subplot(2,2,2)
y2 = sin(2*x);
plot(x,y2)
title('Subplot 2: sin(2x)')
subplot(2,2,3)
y3 = sin(4*x);
plot(x,y3)
title('Subplot 3: sin(4x)')
subplot(2,2,4)
y4 = sin(8*x);
plot(x,y4)
title('Subplot 4: sin(8x)')

suptitle('JaySur:suptitle这行才是总标题')

在这里插入图片描述
上面就是suptitle的使用范例。在默认情况下,suptitle生成的总标题看起来都挺完美的,不过这只是在默认情况下。

但是当figure的背景色是黑色,那就显得非常的糟糕了。请看下图:
在这里插入图片描述
从上图可以看到,当背景色为浅色时,使用suptitle添加总标题看起来还OK,但是当背景色为深色时,就非常的尴尬了。这时候,最佳的选择是使用sgtitle。

sgtitle及其用法

从help系统上可以看到,sgtitle可以配置matlab常规指令中text的所有属性,比如字体颜色、大小、符号、粗斜,甚至外框等等。
在这里插入图片描述
sgtitle放置位置与suptitle相似,必须将其放在所有subplot的最后,示例如下:

figure('Color',[0.314 0.314 0.314]);              
s1=subplot(2,2,1)
x = linspace(0,10);
y1 = sin(x);
plot(x,y1)
set(s1, 'Xcolor', 'white', 'Ycolor', 'white'); 
title('Subplot 1: sin(x)','color','white')

s2=subplot(2,2,2)
y2 = sin(2*x);
plot(x,y2)
set(s2, 'Xcolor', 'white', 'Ycolor', 'white'); 
title('Subplot 2: sin(2x)','color','white')

s3=subplot(2,2,3)
y3 = sin(4*x);
plot(x,y3)
set(s3, 'Xcolor', 'white', 'Ycolor', 'white'); 
title('Subplot 3: sin(4x)','color','white')

s4=subplot(2,2,4)
y4 = sin(8*x);
plot(x,y4)
set(s4, 'Xcolor', 'white', 'Ycolor', 'white'); 
title('Subplot 4: sin(8x)','color','white')

sgtitle('JaySur:sgtitle这行才是总标题','color','white','Fontsize',20)

运行效果如下:
在这里插入图片描述
从上图可以看到,sgtitle比suptitle更能适应多场景的需求。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐