Moritz Braun
Moritz Braun

Reputation: 31

Partially changing the color of text in a text box

I am trying to include a small textbox with a table showing results in a plot. In the table I want to change the text color of only single words or symbols.

The table is created using tabular and LaTeX markup. For some reason some of the commands from the TextBox Properties like \it work, while \color{red} for example doesn't work. Do you know a way to make it colored?

figure
str = '\begin{tabular}{lr} $\it test$ & A \\  $\color{magenta} test$ & A\end{tabular}';  
h = annotation('textbox',[.15 .15 .2 .28],...  
            'Interpreter', 'latex',...
            'FitBoxToText','on',...
            'EdgeColor','black',...
            'BackgroundColor', [1 1 1]);
set(h, 'String', str);

Upvotes: 3

Views: 1023

Answers (2)

gnovice
gnovice

Reputation: 125854

The problem you're running into is that text coloring is only supported when the Interpreter property is set to 'tex', but the tabular environment is only supported when the interpreter is set to 'latex'. Your best workaround is probably to use the jLabel option suggested by Zep.

The only way I can see to do it otherwise is to use the 'tex' interpreter and manage the horizontal element spacing yourself. You can use a cell array of strings to create multi-line text:

str = {'{\it test}   A', '{\color{magenta} test}   A'};
set(h, 'Interpreter', 'tex', 'String', str);

enter image description here

Upvotes: 4

Zep
Zep

Reputation: 1576

You can cheat and use an undocumented jLabel object, which supports HTML markup.

figure
str = '<HTML><FONT color="red">Hello</Font></html>';  
jLabel = javaObjectEDT('javax.swing.JLabel',str);
[hcomponent,hcontainer] = javacomponent(jLabel,[100,100,40,20],gcf);

You can make HTML tables as well:

str = ['<HTML><FONT color="red">Here is a table</Font>'...
       '<table><tr><th>1</th><th>2</th><th>3</th></tr>'...
       '<tr><th>4</th><th>5</th><th>6</th></tr></html>'];  
jLabel = javaObjectEDT('javax.swing.JLabel',str);
[hcomponent,hcontainer] = javacomponent(jLabel,[100,200,150,250],gcf);

You can read more about jLabel components in Matlab here, and about HTML here. Credit goes to Yair Altman's blog.

Upvotes: 5

Related Questions