我正在尝试绘制一个带有 5 x 5 个箭头(总共 25 个)的矢量场。它看起来不错,除了它任意选择“向上”作为 0 矢量的方向。我怎样才能让它完全不显示 0 长度的箭头?
我的代码:
\documentclass{article}
\tikzset{>=stealth}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\draw[->, thick] (-3,0)--(3,0) node[right] {$x$};
\draw[->, thick] (0,-3)--(0,3) node[above] {$y$};
\def\factor{0.15}
\foreach \x in {-2.5,-2,...,2.5} {
\foreach \y in {-2.5,-2,...,2.5}{
\draw[->] (\x,\y)--++(\factor*\y,-\factor*\x);
}
}
\end{tikzpicture}
\end{document}
结果(注意原点的箭头):
答案1
一种可能性是\ifthenelse
:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{ifthen}
\tikzset{>=stealth}
\begin{document}
\begin{tikzpicture}
\draw[->, thick] (-3,0)--(3,0) node[right] {$x$};
\draw[->, thick] (0,-3)--(0,3) node[above] {$y$};
\def\factor{0.15}
\foreach \x in {-2.5,-2,...,2.5} {
\foreach \y [evaluate=\y as \r using int(ceil(abs(\x)+abs(\y)))] in {-2.5,-2,...,2.5}{
\ifthenelse{\r=0}{}{\draw[->] (\x,\y)--++(\factor*\y,-\factor*\x);}
}
}
\end{tikzpicture}
\end{document}
答案2
投入几项\ifx
检查以确认其为零。
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\tikzset{>=stealth}
\newcommand*\zero{0}
\begin{document}
\begin{tikzpicture}
\draw[->, thick] (-3,0)--(3,0) node[right] {$x$};
\draw[->, thick] (0,-3)--(0,3) node[above] {$y$};
\def\factor{0.15}
\foreach \x in {-2.5,-2,...,2.5} {
\foreach \y in {-2.5,-2,...,2.5}{
\def\tmp{\draw[->] (\x,\y)--++(\factor*\y,-\factor*\x)}
\ifx\zero\x\ifx\zero\y\else\tmp\fi\else\tmp\fi;
}
}
\end{tikzpicture}
\end{document}
答案3
\foreach
由于舍入问题,最好避免在 中使用小数。您可以测试\x
和是否都\y
为零:
\documentclass{article}
\usepackage{tikz}
\tikzset{>=stealth}
\begin{document}
\begin{tikzpicture}
\draw[->, thick] (-3,0)--(3,0) node[right] {$x$};
\draw[->, thick] (0,-3)--(0,3) node[above] {$y$};
\def\factor{0.15}
\foreach \x in {-5,-4,...,5} {
\foreach \y in {-5,-4,...,5}{
\pgfmathparse{ifthenelse(and(\x==0,\y==0),1,0)}
\ifnum\pgfmathresult=0
\draw[->] (\x/2,\y/2)--++(\factor*\y/2,-\factor*\x/2);
\fi
}
}
\end{tikzpicture}
\end{document}