2

How do I use the variables of (nested) tikz foreach loops in the legend of a plot in math mode?

This MWE fails:

\documentclass[tikz]{standalone} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \begin{axis} \foreach \a in {1,2}{ \foreach \b in {1,2}{ \addplot {\a*\b*x}; \addlegendentry{$a=\a$, $b=\b$}; % LaTeX Error: Command \$ unavailable in encoding OT1. } } \end{axis} \end{tikzpicture} \end{document} 

This is possibly related to foreach loop in tikz and math mode and How can I use \foreach in math environments?, but those pages don't seem to solve my problem.

1

1 Answer 1

2

You need to expand the content of the entry, for example with

\ExpandArgs {e} \addlegendentry {$a=\a$, $b=\b$} 

\ExpandArgs {⟨spec⟩} {⟨cmd⟩} {⟨arg1⟩} ... is part of the LaTeX kernel and expands the ⟨arguments⟩ of the command ⟨cmd⟩ according the the specification ⟨spec⟩, as documented in the LaTeX usrguide. ⟨spec⟩ consists of one letter per argument, controlling its treatment according to the LaTeX3 programming interface, for example : V for the value of a variable, o for a one-level expansion or e for a full expansion.

Example:

\documentclass[tikz]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis} \foreach \a in {1,2}{ \foreach \b in {1,2}{ \addplot {\a*\b*x}; \ExpandArgs {e} \addlegendentry {$a=\a$, $b=\b$} } } \end{axis} \end{tikzpicture} \end{document} 

Example

5
  • 1
    Thank you very much, this works! Could you elaborate on \ExpandArgs? What does the argument e do? Commented Nov 12, 2024 at 18:57
  • @Roman I added some explanations. By the way, it's better to set the pgfplots compatibility version with \pgfplotsset{compat=<version>} (see tikz.dev/pgfplots/preliminaries-upgrade#pgfplots/compat). Commented Nov 12, 2024 at 20:20
  • ...and probably tex.stackexchange.com/questions/664/… ;-) Commented Nov 12, 2024 at 21:23
  • @Rmano With lualatex we don't need \usepackage[T1]{fontenc}. No? Commented Nov 12, 2024 at 21:30
  • 1
    Yes, correct. I missed the lualatex here... Commented Nov 13, 2024 at 6:47

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.