在里面平均能量损失下面,我制作了一个 TikZ 图片,并bus
使用一个参数调用。该参数在图片内创建节点,这些节点将用作与其他总线的连接点。我想通过它们的连接点(即其中的节点)对齐这些图片。因此,在下面的图片中,右侧的 1 应该与左侧的 2 对齐(垂直居中)。但我希望能够灵活地将右侧总线上的 1 与左侧总线上的 1、2 或 3 对齐。
这可能吗?我认为我尝试的代码失败了,因为对 pic 的定位命令定义了 pic 的原点,所以当时 pic 中没有任何坐标 b-1。这是一个非常简单的例子,虽然我并不习惯使用 pic,但将它们用于这类事情的前景很诱人,可以为复杂的图表构建块。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\begin{document}
\def\busnodespace{3mm}
\tikzset{
pics/bus/.style n args={1}{
code = { %
\draw[ultra thick] (0, {-0.75*\busnodespace}) -- (0, {(#1-1+0.75)*\busnodespace});
\foreach \y in {1,...,#1} {\node[inner sep=0pt] (-\y) at (0.0,{(\y-1)*\busnodespace}) {\color{red}{\scriptsize\y}};}
}}}
\begin{tikzpicture}
\pic (a) at (0,0) {bus=3}; % bus of size 3
% \pic (b) at (2,0) {bus=1}; % bus of size 1 -- is it possible to position this (elegantly, hopefully with no math)
% so coordinate b1 is in line with a2?
% ie I would like a flat line
% \pic[right=of a-2] (b) {bus=1}; % obv this wont cut
\pic[right=of a-2,anchor=b-1] (b) {bus=1}; ; this doesn't work because b isn't made in time for the position to be applied
\draw (a-2) -- (b-1);
\end{tikzpicture}
\end{document}
答案1
像这样?
的定位pic
可能比较棘手,但对于您来说,相对于节点的定位pic
效果很好。在下面的 MWE 中,的代码pic
经过了简化和稍微重组:
\documentclass[border=3.141592, varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{backgrounds, % new
positioning}
\begin{document}
\def\busnodespace{3mm}
\tikzset{
pics/bus/.style ={
code = { %
\foreach \i [count=\y from 0] in {1,...,#1}
{
\node[inner xsep=0pt, inner ysep=\busnodespace/2,
font=\scriptsize, text=red] (-n\i) at (0,\y*\busnodespace) {\i};
}
\scoped[on background layer]
\draw[ultra thick] (-n1.south) -- (-n#1.north);
}
}}
\begin{tikzpicture}
\pic (a) {bus=3}; % bus of size 3
\pic (b) [right=of a-n2] {bus=1}; % bus of size 1
\draw[gray] (a-n2) -- (b-n1);
\end{tikzpicture}
\medskip
\begin{tikzpicture}
\pic (a) {bus=3}; % bus of size 3
\pic (b) [right=of a-n1] {bus=2}; % bus of size 1
\draw[gray] (a-n1) -- (b-n1);
\end{tikzpicture}
\medskip
\begin{tikzpicture}
\pic (a) {bus=3}; % bus of size 3
\pic (b) [right=of a-n3] {bus=1}; % bus of size 1
\draw[gray] (a-n3) -- (b-n1);
\end{tikzpicture}
\end{document}
附录: 还有一个选项。如果你定义 ˙pic` 的锚点,并在其中间设置坐标,那么你可以定位第二张图片,例如:
\documentclass[border=3.141592]{standalone}
\usepackage{tikz}
\usetikzlibrary{backgrounds,
positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 0mm and 15mm,
pics/bus/.style = {code = {\foreach \i [count=\y from 0] in {1,...,#1}
\node[inner xsep=0pt, inner ysep=\busnodespace/2,
font=\scriptsize, text=red] (-n\i) at (0,\y*\busnodespace) {\i};
\scoped[on background layer]
\draw[ultra thick] (-n1.south) -- coordinate (-@c) (-n#1.north);}} % <---
]
\def\busnodespace{3mm}
\pic (a) {bus=2};
\pic (b) [below right=3*\busnodespace and 15mm of a-@c] {bus=3};
\draw[gray] (a-n1) -- (b-n3);
\end{tikzpicture}
\end{document}
使用以下图像主体您将获得相同的结果:
\pic (a) {bus=2};
\pic (b) [right= of a-n1, yshift=-2*\busnodespace] {bus=3};
\draw[gray] (a-n1) -- (b-n3);