我想使用 foreach 和 PGFplots 绘制多条曲线,但每条曲线都有不同的颜色。下面是我给出的代码:
\def\R{1}
\begin{tikzpicture}
\begin{axis}[
xmin = -1.5, xmax = 1.5,
%axis x line*=middle,
ymin = -1.5, ymax = 1.5,
xtick distance = 1,
ytick distance = 1,
xlabel=$x$,
ylabel=$y$,
grid = both,
minor tick num = 2,
major grid style = {lightgray},
minor grid style = {lightgray!25},
width = 0.62\textwidth,
height = 0.62\textwidth]
\addplot[
domain = 0:2*pi,
samples = 200,
smooth,
thick,
] ({\R*sin(deg(x))},{\R*cos(deg(x))});
\foreach \r/\w in {0.1/10,0.2/20}{
\addplot[
domain = 0:2*pi,
samples = 200,
smooth,
thick,
color=red!\w!blue,
] ({(\R-\r)*cos(deg(x))+\r*cos(deg((\R-\r)*x/\r))},{(\R-\r)*sin(deg(x))-\r*sin(deg((\R-\r)*x/\r))});
}
\end{axis}
\end{tikzpicture}
但是,当我在颜色中使用 \w 时,无法编译。有人能帮帮我吗?
答案1
这是因为在axis
环境中使用循环时存在一个常见的“问题”。而且由于它是一个常见的问题,也有一个解决方案......(这是答案的一个变体https://tex.stackexchange.com/a/305183/95441。)
% used PGFPlots v1.17
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\def\R{1}
\begin{axis}[
xmin=-1.5, xmax=1.5,
ymin=-1.5, ymax=1.5,
xtick distance=1,
ytick distance=1,
xlabel=$x$,
ylabel=$y$,
grid=both,
minor tick num=2,
major grid style={lightgray},
minor grid style={lightgray!25},
width=0.62\textwidth,
height=0.62\textwidth,
domain=0:2*pi,
samples=201,
smooth,
]
\addplot[
thick,
] ({\R*sin(deg(x))},{\R*cos(deg(x))});
\foreach \r/\w in {0.1/25,0.2/75}{
\edef\temp{\noexpand%
\addplot[
thick,
color=red!\w!blue,
] (
{(\R-\r)*cos(deg(x)) + \r*cos(deg((\R-\r)*x/\r))},
{(\R-\r)*sin(deg(x)) - \r*sin(deg((\R-\r)*x/\r))}
);
}\temp
}
\end{axis}
\end{tikzpicture}
\end{document}
答案2
使用\pgfplotsinvokeforeach
。
\documentclass[border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\def\R{1}
\begin{tikzpicture}
\begin{axis}[
xmin = -1.5, xmax = 1.5,
%axis x line*=middle,
ymin = -1.5, ymax = 1.5,
xtick distance = 1,
ytick distance = 1,
xlabel=$x$,
ylabel=$y$,
grid = both,
minor tick num = 2,
major grid style = {lightgray},
minor grid style = {lightgray!25},
width = 0.62\textwidth,
height = 0.62\textwidth]
\addplot[
domain = 0:2*pi,
samples = 200,
smooth,
thick,
] ({\R*sin(deg(x))},{\R*cos(deg(x))});
\pgfplotsinvokeforeach{10,20}{
\addplot[
domain = 0:2*pi,
samples = 200,
smooth,
thick,
color=red!#1!blue,
] ({(\R-#1*0.01)*cos(deg(x))+#1*0.01*cos(deg((\R-#1*0.01)*x/(#1*0.01)))},
{(\R-#1*0.01)*sin(deg(x))-#1*0.01*sin(deg((\R-#1*0.01)*x/(#1*0.01)))});
}
\end{axis}
\end{tikzpicture}
\end{document}