我正在使用维恩图来说明两个有限集之间的函数关系。根据集合中的元素数量,我使用的椭圆可能不包含所有元素(及其标签)。如何调整以下代码以使椭圆自动调整大小以包含所有节点及其标签?
\documentclass{article}
\usepackage{pgf,tikz}
\usetikzlibrary{positioning,shapes,fit}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\begin{document}
\begin{tikzpicture}[
every node/.style={on grid},
setA/.style={fill=blue,circle,inner sep=2pt},
setB/.style={fill=red,circle,inner sep=2pt},
every fit/.style={draw,fill=blue!15,ellipse,text width=30pt},
>=latex
]
% set A
\node[setA,label=left:$x$] (x) {};
\node [setA,below = of x,label=left:$y$] (y) {};
\node [setA,below = of y,label=left:$z$] (z) {};
\node[above=of x,anchor=south] {$A$};
% set B
\node[setB,label=right:$10$,right=3cm of x] (10) {};
\node[setB,label=right:$20$, below = of 10] (20) {};
\node[setB,label=right:$30$,below = of 20] (30) {};
\node[setB,label=right:$40$,below = of 30] (40) {};
\node[above=of 10,anchor=south] {$B$};
% the arrows
\draw[->,shorten >= 3pt] (x) -- node[label=above:$f$] {} (10);
\draw[->,shorten >= 3pt] (y) -- node[] {} (10);
\draw[->,shorten >= 3pt] (z) -- node[] {} (30);
% the boxes around the sets
\begin{pgfonlayer}{background}
\node[fit= (x) (z) ] {};
\node[fit= (10) (30) ] {};
\end{pgfonlayer}
\end{tikzpicture}
\end{document}
答案1
您必须命名标签并将其添加到“fit”中
\documentclass{article}
\usepackage{pgf,tikz}
\usetikzlibrary{positioning,shapes,fit}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\begin{document}
\begin{tikzpicture}[
every node/.style={on grid},
setA/.style={fill=blue,circle,inner sep=2pt},
setB/.style={fill=red,circle,inner sep=2pt},
every fit/.style={draw,fill=blue!15,ellipse,text width=30pt},
>=latex
]
% set A
\node[setA,label=left:$x$] (x) {};
\node [setA,below = of x,label=left:$y$] (y) {};
\node [setA,below = of y,label=left:$z$] (z) {};
\node[above=of x,anchor=south,name=A] {$A$};
% set B
\node[setB,label=right:$10$,right=3cm of x] (10) {};
\node[setB,label=right:$20$, below = of 10] (20) {};
\node[setB,label=right:$30$,below = of 20] (30) {};
\node[setB,label=right:$40$,below = of 30] (40) {};
\node[above=of 10,anchor=south] {$B$};
% the arrows
\draw[->,shorten >= 3pt] (x) -- node[label=above:$f$] {} (10);
\draw[->,shorten >= 3pt] (y) -- node[] {} (10);
\draw[->,shorten >= 3pt] (z) -- node[] {} (30);
% the boxes around the sets
\begin{pgfonlayer}{background}
\node[fit= (x) (z) (A)] {};
\node[fit= (10) (30) ] {};
\end{pgfonlayer}
\end{tikzpicture}
\end{document}