我从以下代码中借用了以下代码作为 MWE这里:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes}
\begin{document}
\begin{tikzpicture} [hexa/.style= {shape=regular polygon,regular polygon sides=6,minimum size=1cm, draw,inner sep=0,anchor=south,fill=lightgray!85!blue,rotate=30}]
\foreach \j in {0,...,5}{%
\pgfmathsetmacro\end{5+\j}
\foreach \i in {0,...,\end}{%
\node[hexa] (h\i;\j) at ({(\i-\j/2)*sin(60)},{\j*0.75}) {};} }
\foreach \j in {0,...,4}{%
\pgfmathsetmacro\end{9-\j}
\foreach \i in {0,...,\end}{%
\pgfmathtruncatemacro\k{\j+6}
\node[hexa] (h\i;\k) at ({(\i+\j/2-2)*sin(60)},{4.5+\j*0.75}) {};} }
\end{tikzpicture}
\end{document}
如何根据协调地址改变特定六边形的颜色(h\i;\j)
?
答案1
只需覆盖节点,例如可以使用以下代码覆盖 3-4 节点
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes}
\begin{document}
\begin{tikzpicture} [hexa/.style= {shape=regular polygon,regular polygon sides=6,minimum size=1cm, draw,inner sep=0,anchor=south,fill=lightgray!85!blue,rotate=30}]
\foreach \j in {0,...,5}{%
\pgfmathsetmacro\end{5+\j}
\foreach \i in {0,...,\end}{%
\node[hexa] (h\i;\j) at ({(\i-\j/2)*sin(60)},{\j*0.75}) {};} }
\foreach \j in {0,...,4}{%
\pgfmathsetmacro\end{9-\j}
\foreach \i in {0,...,\end}{%
\pgfmathtruncatemacro\k{\j+6}
\node[hexa] (h\i;\k) at ({(\i+\j/2-2)*sin(60)},{4.5+\j*0.75}) {};} }
\node[hexa,fill=red] at (h3;4.south){};
\end{tikzpicture}
\end{document}
答案2
您可以使用.try
处理程序来覆盖某些特定六边形的样式。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{tikzpicture} [
hexa/.style= {
shape=regular polygon,
regular polygon sides=6,
minimum size=1cm, inner sep=0,
rotate=30,
draw, fill=lightgray!85!blue,
},
h2.3/.style={fill=red}, % <-- new style
h5.4/.style={fill=yellow} % <-- new style
]
\foreach \j in {0,...,5}{%
\pgfmathsetmacro\end{5+\j}
\foreach \i in {0,...,\end}{%
\node[hexa, h\i.\j/.try] (h\i;\j) at ({(\i-\j/2)*sin(60)},{\j*0.75}) {};
}
}
\foreach \j in {0,...,4}{%
\pgfmathsetmacro\end{9-\j}
\foreach \i in {0,...,\end}{%
\pgfmathtruncatemacro\k{\j+6}
\node[hexa,h\i.\k/.try] (h\i;\k) at ({(\i+\j/2-2)*sin(60)},{4.5+\j*0.75}) {};
}
}
\end{tikzpicture}
\end{document}
要绘制六边形,您可以使用一些较短的代码,并改编自这里:
\documentclass[border=7pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\tikzset{
hexagone/.style={
shape=regular polygon,
regular polygon sides=6,
minimum size=1cm, inner sep=0,
rotate=30,
draw, fill=lightgray!85!blue,
h#1/.try,
% label={[red]center:#1} % <- uncoment to see the labels
},
h3/.style={fill=yellow}, % <- custom style
h31/.style={fill=red} % <- custom style
}
\begin{document}
\begin{tikzpicture}
\node[hexagone=0] at (0,0){};
\foreach \r in {1,...,5}
\foreach \t in {0,...,5}
\foreach[evaluate={\l=int(\r*(\r-1)*3+\r*\t+\u)}] \u in {1,...,\r}
\scoped[rotate=-\t*60+30]
\node[hexagone=\l] at (0+.75*\u,{0.43301270189*(2*\r-\u)}){};
\end{tikzpicture}
\end{document}