在使用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更能適應多場景的需求。