我在 Tikz 中使用 \foreach 在一些实数处画一条带有垂直标记的线。但我想在代码中放入 \pi 和 \e(欧拉数),但它不起作用。请问有人能帮助我吗?
我的代码:
\begin{tikzpicture}[scale=1.8]
\draw [->] (-4,0) -- (4,0);
\foreach \x in {-3,-2,-1,0,1,2,3}
\draw[shift={(\x,0)},color=black] (0pt,3pt) -- (0pt,-3pt) node[below] {$\x$};
\foreach \y in {1/2,4/3,-2/3}
\draw[shift={(\y,0)},color=black] (0pt,-3pt) -- (0pt,3pt) node[above] {$\y$};
\end{tikzpicture}
\end{center}
我想:
\begin{tikzpicture}[scale=1.8]
\draw [->] (-4,0) -- (4,0);
\foreach \x in {-3,-2,-1,0,1,2,3}
\draw[shift={(\x,0)},color=black] (0pt,3pt) -- (0pt,-3pt) node[below] {$\x$};
\foreach \y in {1/2,4/3,-2/3, \pi, \e}
\draw[shift={(\y,0)},color=black] (0pt,-3pt) -- (0pt,3pt) node[above] {$\y$};
\end{tikzpicture}
\end{center}
答案1
完全归功于 Alan Munn,他的评论解决了这个问题,这也是为什么这是一个社区维基。除此之外,我不会使用移位(如果您还考虑加载和使用它,最好不要使用\x
)\y
。calc
所以在这里我重新发布了我上面的评论。
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}
\draw [-stealth] (-4,0) -- (4,0);
\foreach \X in {-3,-2,-1,0,1,2,3}
{\draw (\X,3pt) -- (\X,-3pt) node[below] {$\X$};}
\foreach \Y/\Z in {{1/2}/\frac{1}{2},{4/3}/\frac{4}{3},{-2/3}/\frac{-2}{3}, pi/\pi,
e/\mathrm{e}}
{\draw (\Y,-3pt) -- (\Y,3pt) node[above] {$\Z$};}
\end{tikzpicture}
\end{document}
答案2
\documentclass[tikz, margin=3mm]{standalone}
\begin{document}
\begin{tikzpicture}[scale=1.8]
\draw [->] (-4,0) -- (4,0);
\foreach \x in {-3,-2,-1,0,1,2,3}
\draw[shift={(\x,0)}] (0,3pt) -- (0,-3pt) node[below] {$\x$};
\foreach \y [count=\i] in {1/2,4/3,-2/3, e, pi}
{
\draw[shift={(\y,0)}] (0,-3pt) -- (0,3pt)
\ifnum\i=5
node[above] {$\pi$};
\else
node[above] {\y};
\fi
}
\end{tikzpicture}
\end{document}