我正在尝试创建一个如下所示的图表:
我尝试拟合具有越来越多节点的函数,但看起来不正确(在图表上显示所有 3 条曲线以更好地说明):
\documentclass[10pt,landscape,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[UKenglish]{babel}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture} [scale = 0.5]
\foreach \p in {-5,...,5} \node[circle,fill=green] at (\p,2*rand) (\p) {};
\draw [cyan, xshift=4cm] plot [smooth, tension=1] coordinates { (-5) (-4) (-3) (-2) (-1) (0) (1) (2) (3) (4) (5) };
\draw [red, xshift=4cm] plot [smooth, tension=1] coordinates { (-5) (-3) (-1) (1) (3) (5) };
\draw [blue, xshift=4cm] plot [smooth, tension=1] coordinates { (-5) (5) };
\end{tikzpicture}
\end{document}
我也尝试过创建这样的节点(即使用定义函数 x^2+x+1 +“noise”来代替):
\foreach \p in {-5,...,5} \node[circle,fill=green] at (\p, \p * \p + \p + 1 + rand) (\p) {};
但这根本不起作用。
无论如何,我的代码迫使我手动列出节点,这不是很好。
我想我需要一种使用越来越高次数的多项式进行插值的方法?但我不确定该怎么做。
答案1
您可以定义“插值”坐标并将它们与平滑的图连接起来。
\documentclass[10pt,landscape,a4paper]{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture} [scale = 0.5]
\pgfmathtruncatemacro{\imin}{-5}
\pgfmathtruncatemacro{\imax}{5}
\foreach \p in {\imin,...,\imax} \node[circle,fill=green] at (\p,2*rand) (p\p) {};
\foreach \X [evaluate=\X as \Xm using {int(\X-1)},evaluate=\X as \Xp using
{int(\X+1)}] in {\imin,...,\imax}
{\ifnum\X=\imin
\path (p\X) coordinate (i\X);
\else
\ifnum\X=\imax
\path (p\X) coordinate (i\X);
\else
\path (barycentric cs:p\X=0.6,p\Xm=0.2,p\Xp=0.2) coordinate (i\X);
\fi
\fi
}
\draw [blue] plot [smooth, tension=1,variable=\X,samples at={\imin,...,\imax}]
(i\X);
\end{tikzpicture}
\end{document}
当然,除了张力之外,你还可以改变重量。
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\foreach \X in {1,1.5,...,10,9.5,9,...,1.5}
{\begin{tikzpicture}
\pgfmathtruncatemacro{\imin}{-5}
\pgfmathtruncatemacro{\imax}{5}
\pgfmathsetmacro{\mainweight}{\X}
\pgfmathsetseed{27}
\node[anchor=north west,font=\sffamily] at (\imin,-2)
{weight is \pgfmathprintnumber{\mainweight}};
\foreach \p in {\imin,...,\imax} \node[circle,fill=green] at (\p,2*rand) (p\p) {};
\foreach \X [evaluate=\X as \Xm using {int(\X-1)},evaluate=\X as \Xp using
{int(\X+1)}] in {\imin,...,\imax}
{\ifnum\X=\imin
\path (p\X) coordinate (i\X);
\else
\ifnum\X=\imax
\path (p\X) coordinate (i\X);
\else
\path (barycentric cs:p\X=\mainweight,p\Xm=1,p\Xp=1) coordinate (i\X);
\fi
\fi
}
\draw [blue] plot [smooth, tension=0.5,variable=\X,samples at={\imin,...,\imax}]
(i\X);
\end{tikzpicture}}
\end{document}