Ben25
Ben25

Reputation: 131

Adding a text in a plot in MATLAB

How is it possible to add a name in a part of a plot (e.g. in the bottom) alike the image in below:

Upvotes: 0

Views: 4883

Answers (2)

Adam
Adam

Reputation: 2777

By customizing the idea from here we get

x = -10:10;
y = (rand(1,21)-0.5)*20;
figure
plot(x, y, 'pg')
NE = [max(xlim) max(ylim)]-[diff(xlim) diff(ylim)]*0.05;
SW = [min(xlim) min(ylim)]+[diff(xlim) diff(ylim)]*0.05;
NW = [min(xlim) max(ylim)]+[diff(xlim) -diff(ylim)]*0.05;
SE = [max(xlim) min(ylim)]+[-diff(xlim) diff(ylim)]*0.05;

%% Top
text(NE(1), NE(2), 'Top Right', 'VerticalAlignment','top','HorizontalAlignment',...
    'right', 'FontSize',20, 'color', 'red')

text(NE(1)/2 + NW(1)/2, NE(2)/2 + NW(2)/2, 'Top Center', 'VerticalAlignment',...
    'top', 'HorizontalAlignment','center', 'FontSize',20, 'color', 'red')

text(NW(1), NW(2), 'Top Left', 'VerticalAlignment','top', 'HorizontalAlignment',...
    'left', 'FontSize',20, 'color', 'red')

%% Bottom
text(SW(1), SW(2), 'Bottom Left', 'VerticalAlignment','bottom', 'HorizontalAlignment',...
'left', 'FontSize',20, 'color', 'blue')
text(SW(1)/2 + SE(1)/2, SW(2)/2 + SE(2)/2, 'Bottom Center', 'VerticalAlignment',...
    'bottom', 'HorizontalAlignment','center', 'FontSize',20, 'color', 'blue')
text(SE(1), SE(2), 'Bottom Right', 'VerticalAlignment','bottom', 'HorizontalAlignment',...
    'right', 'FontSize',20, 'color', 'blue')

%% Middle
text(NW(1)/2 + SW(1)/2,NW(2)/2 + SW(2)/2, 'Middle Left', 'VerticalAlignment',...
    'top', 'HorizontalAlignment','left', 'FontSize',20)
text(NE(1)/2 + SE(1)/2,NE(2)/2 + SE(2)/2, 'Middle Right', 'VerticalAlignment',...
    'top', 'HorizontalAlignment','right', 'FontSize',20)

text(NE(1)/2 + NW(1)/2 + SW(1)/2 + SE(1)/2,NE(2)/2 + NW(2)/2 + SW(2)/2 + SE(2)/2  , ...
    'Middle Center', 'VerticalAlignment','top', 'HorizontalAlignment','center', 'FontSize',20)

set(gca,'FontSize',20)

enter image description here

Upvotes: 3

Jason K Lai
Jason K Lai

Reputation: 1540

Honestly, I would suggest using the title() or photoshopping the text in post-generation, because MATLAB's implementation has always bee clunky. That being said, MATLAB does have the ability to add text to a figure via the text() command.

The general format is:

text( x, y, '(b) PASCAL-S' );

where the x and y describe the location on the plot that you want to place the text.

Upvotes: 1

Related Questions