\begin{tikzpicture}[
every node/.style={on grid},
setA/.style={circle,inner sep=2pt},
every fit/.style={draw,ellipse,text width=25pt},
>=latex
]
% set A
\node[setA, label=$1$] (a) {};
\node [below = of a,label=$3$] (b) {};
\node [below = of b,label=$5$] (c) {};
\node[above=of a] {$A$};
% set B
\node[inner sep=0pt,right=3cm of a] (x) {$5$};
\node[inner sep=0pt,below = of x] (y) {$12$};
\node[inner sep=0pt,below = of y] (z) {$8$};
\node[above=of x] {$B$};
% the arrows
\draw[->,shorten >= 3pt] (a) -- node {} (x);
\draw[->,shorten >= 3pt] (b) -- node {} (y);
\draw[->,shorten >= 3pt] (c) -- node {} (z);
% the boxes around the sets
\begin{pgfonlayer}{background}
\node[fit= (a) (c) ] {};
\node[fit= (x) (z) ] {};
\end{pgfonlayer}
\end{tikzpicture}
此代码创建了一个函数图。问题在于集合 A 的元素应该位于下方,与集合 B 的元素一样对齐。请帮我修复这些问题。谢谢!
答案1
如果您想涵盖不同的情况,您的代码就不是很通用且调整起来很繁琐。
以下代码解决了您的情况并且更容易调整:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{fit, shapes}
\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \lseti/\lsetmi in {{A}/{1,3,5},{B}/{5,12,8}} {
\begin{scope}[local bounding box=\lseti, x=3cm, y=1cm]
\foreach[count=\j] \lj in \lsetmi {
\node[minimum width=2em] (n-\j-\lseti) at (\i,-\j) {\lj};
}
\end{scope}
\node[ellipse, draw, fit=(\lseti), label={above:$\lseti$}] {};
}
\foreach \i in {1,...,3} {
\draw[->] (n-\i-A) -- (n-\i-B);
}
\end{tikzpicture}
\end{document}