2012-12-01 28 views
0

我試圖找到一個更好的\更緊湊的方式來添加很多「文本塊」(我稱之爲「文本塊」的一些文字有多行)到一個圖。例如參見下面的圖:在Matlab中向圖中添加多個文本塊

enter image description here

我用於生成此圖中的代碼是:

x=-4*pi:pi/20:4*pi; 
y=cos(x); 

% generate positions for the text blocks 
[ypos,xpos]=find(ismember(y,max(y))); % finds multiple maxima 

% generate random data to be presented 
info1=rand(1,numel(xpos));  info2=rand(1,numel(xpos));  info3=rand(1,numel(xpos)); 

plot(x,y); 
ylim([-1.1 1.4]) 

% generate the "text blocks" 
text(x(xpos),ypos+0.3,strcat('A_{',num2str((1:numel(xpos))'),'}=',num2str(info1','%0.1f')),'FontSize',8);  
text(x(xpos),ypos+0.2,strcat('B_{',num2str((1:numel(xpos))'),'}=',num2str(info2','%0.1f')),'FontSize',8);  
text(x(xpos),ypos+0.1,strcat('C_{',num2str((1:numel(xpos))'),'}=',num2str(info3','%0.1f')),'FontSize',8);  
%... 
%... etc 

我知道,多行文本串可以使用單元陣列,通過定義加入一個字符串變量作爲一個單元格數組,每個單元格一行。例如:

text(x,y,{'line 1' ; 'line 2' ; 'line 3'}); 

然而,這也需要每文本塊一行代碼,因此它並不能解決多文本塊的情況下...

我的問題是: 有一種將這些文本塊添加到單行或更一般意義上的方法,比如說,如果我有n個文本塊,每個文本塊都有一些可變數量的文本行?

+0

要點是你想要一種單線版本嗎? – Acorbe

回答

1

什麼

pos = num2cell(linspace(.3,.1,3)); 
lett = num2cell(linspace('A','C',3)); 

your_text_f_handle = @(ps,lt) ... 
    text(x(xpos),ypos+ps,strcat(lt, ... 
    '_{',num2str((1:numel(xpos))'),'}=',... % //REM: old info_i are here 
    num2str(rand(1,numel(xpos))','%0.1f')),'FontSize',8); 

cellfun(your_text_f_handle ,pos,lett); 

它給完全相同的輸出(測試),它是易於擴展。