黎曼和的以下方法首先绘制一条任意曲线(稍后可能会进行调整),然后根据交点形成矩形。不幸的是,填充的矩形会隐藏曲线的某些部分。但是,路径和矩形不能互换,因为矩形取决于路径坐标。如何在不大幅改变方法的情况下避免这个问题?
附言:我尝试在矩形后重新绘制曲线,但出于某种原因,我无法在给定代码之外绘制任何内容,否则会提示错误消息。一定出了问题。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}
%axis
\draw (-.5,0) -- (6.5,0);
%curve
\draw[yshift=1cm,name path=curve] (-.5,0) %vertically shiftable
to[out=70,in=180] (.7,1.5)
to[out=0,in=180] (2,.5)
to[out=0,in=180] (4.5,2.5)
to[out=0,in=160] (6.5,1);
%rectangles
\foreach \x in {0,1,2,5}{
\path[name path=line \x] (\x,0) -- (\x,4);
\path[name intersections={of=curve and line \x, by={isect \x}}];
\draw[fill=gray!50] (isect \x) rectangle (\x+1,0);
\draw[fill] (isect \x) circle [radius=2pt];
}
\end{tikzpicture}
\end{document}
答案1
我不知道是什么导致了之后无法绘制的问题\foreach
,但另一种方法是使用backgrounds
库将矩形放在底层。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{intersections,backgrounds}
\begin{document}
\begin{tikzpicture}
%axis
\draw (-.5,0) -- (6.5,0);
%curve
\draw[yshift=1cm,name path=curve] (-.5,0) %vertically shiftable
to[out=70,in=180] (.7,1.5)
to[out=0,in=180] (2,.5)
to[out=0,in=180] (4.5,2.5)
to[out=0,in=160] (6.5,1);
%rectangles
\begin{scope}[on background layer]
\foreach \x in {0,1,2,5}{
\path[name path=line \x] (\x,0) -- (\x,4);
\path[name intersections={of=curve and line \x, by={isect \x}}];
\draw[fill=gray!50] (isect \x) rectangle (\x+1,0);
\draw[fill] (isect \x) circle [radius=2pt];
}
\end{scope}
\end{tikzpicture}
\end{document}
答案2
使用来自的代码在 tikz 中调用先前命名的路径例如,我们可以在绘制矩形之前定义曲线,但将其渲染延迟至之后。
\documentclass{article}
%\url{https://tex.stackexchange.com/q/150486/86}
\usepackage{tikz}
\usetikzlibrary{intersections}
\makeatletter
\tikzset{
use path for main/.code={%
\tikz@addmode{%
\expandafter\pgfsyssoftpath@setcurrentpath\csname tikz@intersect@path@name@#1\endcsname
}%
},
use path for actions/.code={%
\expandafter\def\expandafter\tikz@preactions\expandafter{\tikz@preactions\expandafter\let\expandafter\tikz@actions@path\csname tikz@intersect@path@name@#1\endcsname}%
},
use path/.style={%
use path for main=#1,
use path for actions=#1,
}
}
\makeatother
\begin{document}
\begin{tikzpicture}
%axis
\draw (-.5,0) -- (6.5,0);
%curve
\path[yshift=1cm,name path=curve] (-.5,0) %vertically shiftable
to[out=70,in=180] (.7,1.5)
to[out=0,in=180] (2,.5)
to[out=0,in=180] (4.5,2.5)
to[out=0,in=160] (6.5,1);
%rectangles
\foreach \x in {0,1,2,5}{
\path[name path=line \x] (\x,0) -- (\x,4);
\path[name intersections={of=curve and line \x, by={isect \x}}];
\draw[fill=gray!50] (isect \x) rectangle (\x+1,0);
\draw[fill] (isect \x) circle [radius=2pt];
}
\draw[use path=curve];
\end{tikzpicture}
\end{document}