Add text annotation with variables to matlab plot over multiple lines

12 views (last 30 days)
I would like to annotate a plot with a textbox (with or without a visible box) with the following characteristics
  • Use latex as interpreter
  • Have variable inputs (i.e. taken from values within matlab environment)
  • Allow for line breaks where I want them
I have managed to do parts of this, but not all at the same time.
What I have tried:
alpha = 2;
plot(1:10)
text(2,5,'$\alpha = $','Interpreter','latex')
allows me to add the \alpha to the point of interest but I cannot figure out how to also have the variable alpha value
figure
plot(1:10)
dim = [0.179 0.849 0.06 0.037];
str = strcat('\alpha = ',num2str(alpha));
annotation('textbox',dim,'String',str,'FitBoxToText','on','Interpreter','latex');
allows me to include the variable alpha value, but I don't have the latex formatting on \alpha (I presume because of the strcat).
I tried a few suggestions around char(10) and \n to get newlines, but unsuccessfully.
I would appreciate an example of how to annotate this plot (plot(1:10)) with the an annotation that has \alpha = ALPHA on one line and \beta = BETA on the next line where the values for ALPHA and BETA are defined in the code.
Apologies for the basic question, it has been asked many times but I was unable to find a simple example to demonstrate how this worked with all my requirements.

Answers (1)

Samayochita
Samayochita on 6 Feb 2025
Hi Esme,
The issue arises because MATLAB interprets “strcat as a standard character string, which disrupts LaTeX rendering. Additionally, inserting line breaks using “char(10)” or “\n” does not work properly with LaTeX in “annotation”.
Instead of concatenating strings, you could try using a cell array, which MATLAB naturally interprets as separate lines in an annotation. Here’s a working example:
alpha = 2;
beta = 3;
plot(1:10)
% Define the annotation text as a cell array
str = {'$\alpha = 2.00$', '$\beta = 3.00$'};
% Add the annotation with LaTeX interpreter
annotation('textbox', [0.15, 0.8, 0.1, 0.1], 'String', str,'FitBoxToText', 'on', 'Interpreter', 'latex');
The $...$ syntax ensures \alpha and \beta are rendered correctly. Instead of “strcat, the variable values are directly placed in a formatted string within the cell array.
This method correctly annotates the plot with a multi-line LaTeX formatted textbox. I hope this helps in solving the issue at your end.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!