答案1
这是一个带有轴宏和函数的解决方案,它还可以创建有助于绘制矩形或梯形的节点:
代码:
\documentclass[tikz,border=2mm]{standalone}
\tikzset{declare function={f(\x)=0.25*(\x-2.5)^3-0.75*\x+5);}}
\newcommand{\myfunction}[2]
{
\begin{scope}[shift={(#1,0)}]
\draw[-latex] (-0.5,0) -- (5,0) node[below] {$x$};
\draw[-latex] (0,-0.5) -- (0,5) node[left] {$y$};
\draw[thick,cyan] plot[domain=0.5:4.5,samples=41] (\x,{f(\x)});
\node at (3.25,3.5) {$y=f(x)$};
\foreach\i in {0,1,2,3,...,8}
{
\pgfmathsetmacro\j{0.5*\i+0.5}
\coordinate (x\i) at (\j,0);
\coordinate (y\i) at (\j,{f(\j)});
}
\foreach\i in {0,1,2}
\node[below] at (x\i) {$x_\i$};
\node[below] at (x7) {$x_{n-1}$};
\node[below] at (x8) {$x_n$};
\node[yshift=-0.75cm] at (x0) {\strut$a$};
\node[yshift=-0.75cm] at (x8) {\strut$b$};
\node[yshift=-1cm] at (x4) {(#2)};
\end{scope}
}
\begin{document}
\begin{tikzpicture}[line join=round,line cap=round,scale=1.25]
% left
\myfunction{0}{A}
\foreach\i in {0,1,2,3,7}
{
\pgfmathtruncatemacro\j{\i+1}
\draw[gray] (x\j) rectangle (y\i);
\fill (y\i) circle (1pt);
}
% center
\myfunction{6}{B}
\foreach\i in {0,1,2,3,7}
{
\pgfmathtruncatemacro\j{\i+1}
\draw[gray] (x\i) rectangle (y\j);
\fill (y\j) circle (1pt);
}
% right
\myfunction{12}{C}
\foreach\i in {0,1,2,3,7,8}
{
\pgfmathtruncatemacro\j{\i+1}
\ifnum\i<8
\draw[gray] (x\i) -- (y\i) -- (y\j) -- (x\j);
\fi
\fill (y\i) circle (1pt);
}
\end{tikzpicture}
\end{document}