答案1
我的示例主要依赖于 tikz 库的功能math
并明确执行大多数计算。
f
为了正确输出,代码需要五个参数:要绘制的函数、df
函数的导数、 y 轴的最大值ymax
、 x 间隔以及应绘制加号或减号的interval
点数。N
\documentclass[10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{math, calc}
\tikzmath{
\ymax = 1.6;
\N = 28;
\interval = 3/2*pi+0.2;
\k = 2;
%
function f(\x) {
sin(\k*\x*180/pi-90);
};
%
function df(\x) {
return(\k*cos(\k*\x*180/pi-90));
};
%
\xmax = \interval/2+0.3;
\xmin = -\xmax;
\ymin = -\ymax;
}
\tikzset{
sign/.style = {
font=\tiny
},
minus sign/.style = {
sign, text=red!90!black, anchor=south
},
plus sign/.style = {
sign, text=green!60!black, anchor=north
}
}
\begin{document}
\begin{tikzpicture}
\begin{scope}[local bounding box=graph]
\draw[->] (0,\ymin) -- (0,\ymax) node[above]{$y$};
\draw[->] (\xmin,0) -- (\xmax,0) node[right]{$x$};
\draw[domain=-\interval/2:\interval/2, samples=100] plot(\x, {f(\x)});
\path[clip] (\xmin,\ymin) rectangle (\xmax,\ymax);
\tikzmath{
for \i in {0,...,\N}{
\x = \i/\N*\interval-\interval/2;
\y = f(\x);
\angle = atan(df(\x))-90;
if f(\x) > 0.25 then {
{
\path (\x,\y) -- ++(\angle:0.01) node[plus sign]{$+$};
};
} else {
if f(\x) < -0.25 then {
{
\path (\x,\y) -- ++(\angle-180:0.01) node[minus sign]{$-$};
};
};
};
};
}
\end{scope}
\draw ($(graph.south east)+(1,-1)$) rectangle ($(graph.north west)+(-1,1)$);
\end{tikzpicture}
\end{document}