Reputation: 26069
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:
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?
Upvotes: 0
Views: 5287
Reputation: 8391
What about
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);
it gives exactly the same output (tested) and it is easily extendable.
Upvotes: 1