pgfplots 图例删除花括号的奇怪问题

pgfplots 图例删除花括号的奇怪问题

编译以下内容时

\documentclass{article}

\usepackage{amsmath}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[domain=-1:1]
        \addplot { ifthenelse(x < 0, 0, x) };
        \legend{$\text{ReLU}(x):=\max\{0, x\}$}
    \end{axis}
\end{tikzpicture}

\end{document}

使用 TeXLive 2023 时,我收到以下错误:

! Extra }, or forgotten $.
\pgfplots@already@computed@legend@node ...max \{0}
                                                  ;\\};
l.13     \end{axis}
                   
I've deleted a group-closing symbol because it seems to be
spurious, as in `$x}$'. But perhaps the } is legitimate and
you forgot something else, as in `\hbox{$x}'. In such cases
the way to recover is to insert both the forgotten and the
deleted material, e.g., by typing `I$}'.

! Missing } inserted.
<inserted text> 
                }
l.13     \end{axis}
                   
I've put in what seems to be necessary to fix
the current column of the current alignment.
Try to go on, since this might almost work.

错误表明它有“删除了组结束符号”我认为不应该这样,因为$\text{ReLU}(x):=\max\{0, x\}$在文本中单独使用它就可以了。

这里的问题到底是什么?我该如何解决它或告诉它不要删除}

答案1

与往常一样,在参数中隐藏 tex 分隔符时,您可以使用组,{}因为分隔符仅在顶层被识别,例如

\documentclass{article}

\usepackage{amsmath}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[domain=-1:1]
        \addplot { ifthenelse(x < 0, 0, x) };
        \legend{${\text{ReLU}(x):=\max\{0, x\}}$}
    \end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案2

更新:这是一种放置节点的方法,它接受文本 pgfplot 会认为“很奇怪”,无需任何进一步的样式,例如绘制其形状等。

\documentclass{article}

\usepackage{amsmath}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
        domain=-1:1,
        legend style={
            at={(0.05,.95)},
            anchor=north west,
        },
        xlabel=x,
        ylabel=y(x),
    ]
        \addplot { ifthenelse(x < 0, 0, x) };
        \legend{
            $y(x) := (x \le 0 \quad ? \quad 0 : x)$
        }
        \node[anchor=west] 
            at (axis cs:-1.1,.4) {$\text{ReLU}(x):=\max\{0, x\}$};
    \end{axis}
\end{tikzpicture}

\end{document}

结果2


这是使用 Perlish 来实现此目的的方法,仅用于表达 if-then-else 短语,因为这里的语法似乎很棘手:

\documentclass{article}

\usepackage{amsmath}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
        domain=-1:1,
        legend style={
            at={(0.05,.95)},
            anchor=north west,
        },
        xlabel=x,
        ylabel=y(x),
    ]
        \addplot { ifthenelse(x < 0, 0, x) };
        \legend{
            $y(x) := (x \le 0 \quad ? \quad 0 : x)$
        }
    \end{axis}
\end{tikzpicture}

\end{document}

结果

相关内容