我想制作一个树,每个节点的价数为 3。我在网上找到了以下代码。第一级的价数为 3,而第二级和第三级的价数为 4,我还想将子节点的颜色与父节点不同,并且只想使用三种颜色。(例如,如果父节点是红色,那么分支将是绿色和蓝色)
\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{trees,snakes}
\begin{document}
\pagestyle{empty}
\tikzstyle{level 1}=[level distance= 32mm,sibling angle=120]
\tikzstyle{level 2}=[level distance= 16mm,sibling angle=60]
\tikzstyle{level 3}=[level distance = 12mm,sibling angle=30]
\tikzstyle{every node}=[fill]
%\tikzstyle{edge from parent}=[segment length=1mm,
% segment angle=10,draw]
\begin{tikzpicture}[grow cyclic,shape=circle,very thick,level distance=13mm,
cap=round]
\node {} child [color=\A] foreach \A in {red,green,blue}
{ node {} child [color=\A!50!\B] foreach \B in {red, green,blue}
{ node {} child [color=\A!50!\B!50!\C] foreach \C in {red,green,blue}
{ node {} }
}
};
\end{tikzpicture}
我是 tikz 的新用户,到目前为止,我对它的使用还不太熟悉。
答案1
非常类似于Andrew 的回答很好除了父母和孩子的颜色不同之外。编辑:删除了多余的\index
,非常感谢安德鲁!@nd 编辑:用 简化\pgfkeysalso
。
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{trees,snakes}
\begin{document}
\pagestyle{empty}
\xdef\mycolor{black}
\xdef\ColorList{{"red","green!60!black","blue"}}
\tikzset{level 1/.style={level distance= 32mm,sibling angle=120},
level 2/.style={level distance= 16mm,sibling angle=60},
level 3/.style={level distance = 12mm,sibling angle=30},
every node/.append style={fill},
my color/.code={\pgfmathparse{\ColorList[mod(#1,3)]}
\pgfkeysalso{/tikz/color/.expanded=\pgfmathresult}}}
\begin{tikzpicture}[grow cyclic,shape=circle,very thick,level distance=13mm,
cap=round]
\node {} child [my color=\A] foreach \A in {0,1,2}
{ node {} child [my color=\A+\B+1] foreach \B in {0,1}
{ node {} child [my color=\A+\B+\C+2] foreach \C in {0,1}
{ node {} }
}
};
\end{tikzpicture}
\end{document}
答案2
如果你希望每个顶点的价数为 3,那么你应该只循环子节点的两种颜色。这样可以得到:
修改后的代码如下:
\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{trees,snakes}
\begin{document}
\pagestyle{empty}
\tikzstyle{level 1}=[level distance= 32mm,sibling angle=120]
\tikzstyle{level 2}=[level distance= 16mm,sibling angle=60]
\tikzstyle{level 3}=[level distance = 12mm,sibling angle=30]
\tikzstyle{every node}=[fill]
%\tikzstyle{edge from parent}=[segment length=1mm,
% segment angle=10,draw]
\begin{tikzpicture}[grow cyclic,shape=circle,very thick,level distance=13mm,
cap=round]
\node {} child [color=\A] foreach \A in {red,green,blue}
{ node {} child [color=\A!50!\B] foreach \B in {red, green}
{ node {} child [color=\A!50!\B!50!\C] foreach \C in {red,green}
{ node {} }
}
};
\end{tikzpicture}
\end{document}