因此,我尝试为帕斯卡三角形生成 tikzpicture。这是我目前的代码和结果:
\begin{figure}
\centering
\begin{tikzpicture}
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\pgfmathsetmacro\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
};
};
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\kp{\k+1}
\pgfmathsetmacro\np{\n+1}
\draw[->] (a\k\n.center) -- (a\k\np);
};
};
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
但是,我希望中心之间有连接,因此我添加了“.center”来绘制到中心锚点的线条:
\begin{figure}
\centering
\begin{tikzpicture}
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\pgfmathsetmacro\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
};
};
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\kp{\k+1}
\pgfmathsetmacro\np{\n+1}
\draw[->] (a\k\n.center) -- (a\k\np.center);
};
};
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
如何修复它/哪里出了问题?为什么可以a\k\n.center
正常工作,但a\k\np.center
不能?
答案1
您不需要\pgfmathsetmacro
,而是\pgfmathtruncatemacro
想要获得一个整数表示。类似地,二项式系数值的宏可以/应该用 来定义\edef
。
顺便说一句,最好定义一种样式,而不是重复长长的选项列表:这样更易于管理。此外,\foreach
循环不是 PGF 语句,因此它们后面不应跟分号(您会收到大量关于;
不存在的警告\nullfont
)。
\documentclass{article}
\usepackage[a4paper,margin=1cm]{geometry}
\usepackage{amsmath}
\usepackage[dvipsnames]{xcolor}
\usepackage{xintexpr}
\usepackage{tikz}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}[
rect/.style={rectangle,minimum height=1cm,minimum width=1cm,draw,fill=Red!\nten}
]
\foreach \n in {0,...,7}{
\foreach \k in {0,...,\n}{
\pgfmathsetmacro\nten{\n * 8}
\node[rect] (a\k\n) at (\k-\n/2,7-\n) {$\binom{\n}{\k}$};
\edef\currbinom{\xinttheiiexpr binomial(\n,\k)\relax}
\node[rect] (b\k\n) at (\k-\n/2+10,7-\n) {$\currbinom$};
}
}
%verbindungen
\foreach \n in {0,...,6}{
\foreach \k in {0,...,\n}{
% \pgfmathtruncatemacro\kp{\k+1}
\pgfmathtruncatemacro\np{\n+1}
\draw[->] ({a\k\n}.center) -- ({a\k\np}.center);
}
}
\node[rectangle] (eqsign) at (5,4) {$=$};
\end{tikzpicture}
\caption{Caption}
\label{fig:pascal-tri}
\end{figure}
\end{document}