Search code examples
matlabplotmatlab-figure

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:


Solution

  • 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