0

I'm trying to find a better \ more compact way to add many "text blocks" (I call a "text block" some text that has multiple lines) to a figure. See for example the figure below:

enter image description here

The code I used to generate this figure is:

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

I'm aware that multiline text strings can be added using cell arrays, by defining a string variable as a cell array with one line per cell. For example:

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

However, this also requires one line of code per text block, so it doesn't solve the multi text blocks case ...

my question is: Is there a way to add these text blocks in a single line or in a more generic sense, say if I have n text blocks each with some variable number of lines of text?

4

1 回答 1

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);

它提供完全相同的输出(经过测试),并且易于扩展。

于 2012-12-01T12:25:48.340 回答