Add text annotation with variables to matlab plot over multiple lines

13 ビュー (過去 30 日間)
Esme
Esme 2017 年 3 月 31 日
回答済み: Samayochita 2025 年 2 月 6 日
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.

回答 (1 件)

Samayochita
Samayochita 2025 年 2 月 6 日
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.

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by