考虑以下使用 TikZ 绘制图形的代码:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{graphs,graphs.standard}
\begin{document}
\begin{tikzpicture}
\graph [nodes={draw, circle}, clockwise, radius=.75cm, empty nodes, n=4] {
subgraph C_n [name=inner] -- [shorten <=1pt, shorten >=1pt]
subgraph C_n [name=outer]
};
\end{tikzpicture}
\end{document}
这是根据文档改编的。有没有一种很好的方法来获得图形着色此图(有两种颜色)。也就是说,没有两个通过边连接的顶点具有颜色?
因为这是对我实际尝试做的事情的简化,所以我更希望找到一个不手动放置顶点,除非有自动方法。具体来说,我正在寻找一种不让我们想到 n=4 的解决方案。
答案1
这是您示例的偶数图形的解决方案n
。如果n
是奇数,则没有这样的着色。
我使用math
库来制定逻辑,但如果你愿意,你可以用 vanilla tex 解决方案替换这部分代码。
\documentclass[tikz, border=7pt]{standalone}
\usetikzlibrary{graphs,graphs.standard,math}
\xdef\j{0} % the node number is stored globally
\tikzset{
color0/.style = {fill=red!35},
color1/.style = {fill=blue!35},
setcolor/.code = {
\tikzmath{
int \j, \k;
\j = \j+1;
\k = mod((\j <= #1 ? \j+1:\j), 2);
}
\xdef\j{\j}
\pgfkeysalso{node contents=\j, color\k}
},
graphs/mygraph/.style = {
nodes={draw, circle, setcolor=#1}, clockwise, radius=#1*.25cm, empty nodes, n=#1
}
}
\begin{document}
\begin{tikzpicture}
\graph [mygraph=4] {
subgraph C_n [name=inner] -- [shorten <=1pt, shorten >=1pt]
subgraph C_n [name=outer]
};
\end{tikzpicture}
\end{document}
和mygraph=10
:
编辑(这个答案被接受之后): 这里有一个不带 的代码tikzmath
,这样节点计数器就会在图形开始时自动重置。这样您就可以绘制多个图形,而无需手动重置计数器。
\documentclass[tikz, border=7pt]{standalone}
\usetikzlibrary{graphs,graphs.standard}
\newcount\nodenum % the node number is stored globally
\tikzset{
color0/.style = {fill=red!35},
color1/.style = {fill=blue!35},
setcolor/.code = {
% if we start the second part
\ifnum \nodenum = #1
\global\advance\nodenum 1\relax
\fi
% set the color
\pgfmathparse{int(mod(\nodenum, 2))}
\pgfkeysalso{color\pgfmathresult, node contents=\the\nodenum}
% count this node and save globally
\global\advance\nodenum 1\relax
},
graphs/mygraph/.style = {
nodes={draw, circle, setcolor=#1}, clockwise, radius=#1*.25cm, empty nodes, n=#1
},
graphs/mygraph/.append code={
\global\nodenum 0\relax % reset the counter at the beginning
}
}
\begin{document}
\begin{tikzpicture}
\graph [mygraph=4] {
subgraph C_n [name=inner] -- [shorten <=1pt, shorten >=1pt]
subgraph C_n [name=outer]
};
\graph [mygraph=12] {
subgraph C_n [name=inner] -- [shorten <=1pt, shorten >=1pt]
subgraph C_n [name=outer]
};
\end{tikzpicture}
\end{document}