在循环 PGFplots 中插入图例

在循环 PGFplots 中插入图例

我想迭代地为图片添加图例。我的代码是:

\documentclass[11pt,border=10mm]{standalone}
\usepackage[portuguese]{babel} 
\usepackage[utf8]{inputenc}
\usepackage{tikz,pgfplots}
\usepgfplotslibrary{polar}

\begin{document}

\begin{tikzpicture}[scale=0.9]
    \begin{polaraxis}[title={$r=\cos n \theta$}, xlabel=$r$,ylabel=$\theta$,ytick distance=0.5,xtick distance=15,samples=600,legend style={at={(0.5,-0.1)},anchor=north,legend columns = 2},]
        \foreach \n\w in {1/0,2/33,3/66,4/99}{
            \edef\contador{\noexpand 
            \addplot[color=red!\w!blue,line width=2pt,mark=none,domain=-360:360] (x,{cos(\n*x)});
            }\contador           
        }
        \legend{$n=1$,$n=2$,$n=3$,$n=4$}
    \end{polaraxis}
\end{tikzpicture}

\end{document}

我不想像这样插入图例:\legend{$n=1$,$n=2$,$n=3$,$n=4$}而是在循环内。我该怎么做?

答案1

只需添加\addlegendentry

\documentclass[11pt,border=10mm]{standalone}
%\usepackage[portuguese]{babel} 
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepgfplotslibrary{polar}

\begin{document}

\begin{tikzpicture}[scale=0.9]
    \begin{polaraxis}[title={$r=\cos n \theta$}, xlabel=$r$,ylabel=$\theta$,ytick distance=0.5,xtick distance=15,samples=600,legend style={at={(0.5,-0.1)},anchor=north,legend columns = 2},]
        \foreach \n\w in {1/0,2/33,3/66,4/99}{
            \edef\contador{\noexpand 
            \addplot[color=red!\w!blue,line width=2pt,mark=none,domain=-360:360] (x,{cos(\n*x)});
            \noexpand\addlegendentry{$n=\n$}
            }\contador           
        }
    \end{polaraxis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容