我正在尝试绘制如下图表:
到目前为止我得到的是:
不知道左上角那个小盒子是从哪里来的......
这是我的代码:
\documentclass[a4paper,10pt]{article}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,arrows,positioning,chains}
\begin{document}
\tikzset{
block/.style={
rectangle,
draw,
text width=10em,
text centered,
rounded corners
},
}
\begin{tikzpicture}
\matrix (m)[matrix of nodes, column sep=1cm,row sep=8mm, align=center, nodes={rectangle,draw, anchor=center} ]{
& |[block]| {1}
& \\
& & \\
|[block]| {1}
& |[block]| {2}
& |[block]| {3} \\
};
\draw [>=latex,-] (m-1-2) |- (m-3-1);
\end{tikzpicture}
\end{document}
当我尝试从顶部框绘制到中间的矩阵元素时,出现错误消息“没有已知名为 m-2-2 的形状”。
我该怎么办?谢谢
答案1
- 您有空行
matrix
,这是导致图像中出现不想要的正方形的原因(在矩阵中您没有空行) - 对于所有单元格的命名,您需要
nodes in empty cells,
向matrix
样式选项中 - 在空单元格中没有绘制小方块,你必须将
nodes
样式更改为coordinate
:
\documentclass[a4paper,10pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,
chains,
matrix,
positioning}
\begin{document}
\tikzset{
block/.style={
rectangle,
draw,
text width=10em,
text centered,
rounded corners
},
}
\begin{tikzpicture}
\matrix (m) [matrix of nodes,
nodes in empty cells,
column sep=1cm,
row sep=8mm,
align=center,
nodes={coordinate}
]
{
& |[block]| {1} & \\
& & \\
|[block]| {1} & |[block]| {2} & |[block]| {3} \\
};
\draw (m-1-2) -- (m-2-2) -| (m-3-1)
(m-2-2) -| (m-3-2)
(m-2-2) -| (m-3-3);
% or
% \draw (m-1-2) -- (m-3-2)
% (m-3-1) |- (m-2-2) -| (m-3-3);
\end{tikzpicture}
\end{document}
(在您的图像中的节点较高,但在 MWE 中您没有定义它们的高度。我遵循您 MWE 中的节点样式定义。)
但是,您的图是树,可以更简单地绘制为树,例如使用森林包:
%\documentclass[a4paper,10pt]{article}
\documentclass[margin=3.141592]{standalone}
\usepackage[edges]{forest}
\begin{document}
\begin{forest}
for tree={
% style of nodes
draw, semithick, rounded corners,
text width = 4em, text badly centered,% changed
minimum height = 4ex, % added
% style of tree
edge = {draw=blue}, % changed
anchor = north,
grow = south,
forked edge,
s sep = 4mm, % horizontal ("sibling") distance between nodes
l sep = 12mm, % vertical ("level") distance between n odes
fork sep = 6mm, % distance from parent to branching point
}
[1
[1]
[2]
[3]
]
\end{forest}
\end{document}
绘制了下面的树:
答案2
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta, positioning, shapes}
\begin{document}
\begin{tikzpicture}[
node distance = 1.5cm and 1cm,
arr/.style = {draw=blue!50, ultra thick},
base/.style = {draw, font=\small,
minimum height=3em, text width=5em, align=center},
block/.style = {base, fill=#1},
block/.default = white,
every edge/.append style = {arr}
]
\node [block] (A) {};
\node [block, below =of A] (B) {};
\node [block, right = of B] (C) {};
\node [block, left = of B] (D) {};
\coordinate[below=1cm of A] (aux);
\path[arr] (A) to (B);
\path[arr](aux) -| (C);
\path[arr](aux) -| (D);
\end{tikzpicture}
\end{document}