我正在尝试使用 pgfplots 生成几个相交的峰值,并在它们重叠的地方使用虚线/点线路径。不过,我在 foreach 循环中的路径名方面遇到了一些问题。以下是代码:
\documentclass[tikz]{standalone}
\usepackage{tikz, pgfplots}
\usetikzlibrary{positioning, intersections}
\usepgfplotslibrary{fillbetween}
\pgfmathdeclarefunction{peak}{1}{%
\pgfmathparse{abs(#1) > 1 ? 0 : cos((0.5*pi*#1) r)^3}%
}%
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=400pt, height=250pt]
% overlapping peaks
\pgfplotsinvokeforeach{-1,0,1}{
\addplot [name path global = { line#1 },
domain=#1-1:#1+1, samples=20, smooth, thick, black]
{peak(x-#1)};
}
\path[draw=white, dotted, ultra thick,
intersection segments={of=line1 and line0}];
\path[draw=white, dotted, ultra thick,
intersection segments={of=line0 and line-1}];
\end{axis}
\end{tikzpicture}
\end{document}
我想将最后两个path
调用放在某种循环中。问题是如何获取行名称。line#1 and line#1-1
在 pgfplots foreach 中尝试过,但不起作用(显然?我仍然不太清楚数学在 pgf 中哪里有效,哪里无效),line\i and line\i-1
在\foreach \i
循环中尝试过。也不起作用...
还尝试将减法放在一\pgfmathparse{int(#1-1)}\pgfmathresult
对中,但总是抱怨缺少\endcsname
。
有什么想法吗?此外,任何关于如何实现我想要的更好方法的建议都非常受欢迎...谢谢!
答案1
\path
见下文。这通过在调用之前完全展开参数来实现。请注意,您%
在左括号处缺少一个,peak
这会移动整个图。
\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{positioning,intersections}
\usepgfplotslibrary{fillbetween}
\pgfmathdeclarefunction{peak}{1}{%
\pgfmathparse{abs(#1) > 1 ? 0 : cos((0.5*pi*#1) r)^3}%
}%
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=400pt, height=250pt]
% overlapping peaks
\pgfplotsinvokeforeach{-1,0,1}{%
\addplot [name path = { line#1 },
domain=#1-1:#1+1, samples=20, smooth, thick, black]
{peak(x-#1)};
}
\foreach \x in {0,...,1}{%
\pgfmathparse{int(\x-1)};
\def\arg{of=line\x\space and line\pgfmathresult}%
\edef\expath{\noexpand\path[draw=white, dotted, ultra thick,
intersection segments={\arg}];}
\expath%
}
\end{axis}
\end{tikzpicture}
\end{document}
答案2
A元帖子替代方案。更简单的语法?您决定。我稍微作弊了,只绘制了一条曲线,然后通过简单地左右移动来复制它。MPintersectiontimes
手册中解释了它的工作原理。
prologues := 3;
outputtemplate := "%j%c.eps";
beginfig(1);
vardef f(expr x) = if abs x > 1: 0 else: (cosd(90x))**3 fi enddef;
path xx, yy, line[];
xx = (left--right) scaled 220 shifted 20 down;
yy = (origin--up) scaled 180 shifted point 0 of xx;
drawarrow xx withcolor .5 white;
drawarrow yy withcolor .5 white;
s = 1/32;
line2 = ((-1,f(-1)) for x=s-1 step s until 1: -- (x,f(x)) endfor) yscaled 150 xscaled 100;
line1 = line2 shifted 100 left;
line3 = line2 shifted 100 right;
numeric t[];
(t1,t2) = line1 intersectiontimes line2;
(t3,t4) = line2 intersectiontimes line3;
drawoptions(withcolor .67 red);
draw subpath( 0,t1) of line1;
draw subpath(t2,t3) of line2;
draw subpath(t4,infinity) of line3;
drawoptions(dashed withdots scaled 0.7);
draw subpath(t1,infinity) of line1;
draw subpath(t3,infinity) of line2;
draw subpath(0,t2) of line2;
draw subpath(0,t4) of line3;
drawoptions();
endfig;
end.