Search code examples
matlabcolorstextboxmatlab-figurefigure

Long colored line in textbox


I want to indicate the meaning of different text colors in my plot in a textbox.

Here a sample code:

figure;
bar([1,2,3])
ylim([0 5]); text(1,2,'{\color{blue} apples} {\color{red} pears}');
annotation('textbox',[.2 .6 .3 .3],'String',{'yes','no'},'FitBoxToText','on' );

All I'm looking for is an adequate symbol such as a long bold line or a square to use it as a color marker in my textbox in front of 'yes' and 'no'. Similar to the colored lines in a legend. How do I implement this in a MATLAB textbox?

Note: None of the special characters from the MATLAB webpage seems to be of use for me.


Solution

  • I have provided some alternatives but to me the bullet seems appropriate among the special characters listed in the link you mentioned. Check the result below:

    figure;
    bar([1,2,3])
    ylim([0 5]); text(1,2,'{\color{blue} apples} {\color{red} pears}');
    annotation('textbox',[0.2 0.6 0.3 0.3],'String',{['{\color{blue}','\bullet','} yes'],...
        ['{\color{red}','\bullet','} no']},'FitBoxToText','on');
    

    which gives:

    output1


    If you're a fan of unicodes, you have more freedom. You can insert any of hyphen (-), em dash (—), square (■), bullet (•) and the list goes on.

    char(8212) gives em dash, char(9632) gives square, and char(8226) gives bullet. Use whichever you want.

    figure;
    bar([1,2,3])
    ylim([0 5]); text(1,2,'{\color{blue} apples} {\color{red} pears}');
    annotation('textbox',[0.2 0.6 0.3 0.3],'String',{['{\color{blue}',char(8212),'} yes'],...
        ['{\color{red}',char(9632),'} no']},'FitBoxToText','on'); 
    

    which gives:

    output2


    or you can manipulate legend into producing the required result as shown below:

    figure;
    plot(NaN,NaN,'b',NaN,NaN,'r'); hold on;    %The trick
    bar([1,2,3])
    ylim([0 5]); text(1,2,'{\color{blue} apples} {\color{red} pears}');
    legend({'yes','no'},'Location','northwest');
    

    which gives:

    output3