![仅在当前 tikzpicture 内定义一个 tikz 变量](https://linux22.com/image/458837/%E4%BB%85%E5%9C%A8%E5%BD%93%E5%89%8D%20tikzpicture%20%E5%86%85%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%20tikz%20%E5%8F%98%E9%87%8F.png)
我想在我的 tikzpicture 中“定义”一个变量。这回答给出了如何使用math
库来实现这一点的解决方案。
我关心的是,当我分配\x1
值时1
,假设这个值在我的乳胶文档中是全局定义的。
因此,如果我想绘制两个相当相似的图形,并且都可以用名称x1
来描述特定长度,那么我需要
- 为这个长度想出一个新名字,
x1
例如x1new
\x1=1
或者我需要在文档的后面部分重复该定义\x1=2
。
我的问题是是否有办法定义一个变量并为其赋值只针对当前 tikzpicture
环境?
一位 MWE 表示:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{math}
\tikzmath{\x1 = 2; \y1=1;} %%%% <<----- First definition
\begin{document}
In this lecture we will talk about complex numbers.
The complex number $2+\mathrm{i}$ can be pictured in the following way:
\begin{tikzpicture}
\draw[step=.5cm,gray,very thin] (-2.4,-2.4) grid (2.4,2.4);
\draw [-latex] (-2.5,0) -- (2.5,0);
\draw [-latex] (0,-2.5) -- (0,2.5);
\draw [thick, - latex] (0,0) -- (\x1,\y1);
\end{tikzpicture}
An example for a vector with a negative argument is the following:
\begin{tikzpicture}
\tikzmath{\y1=-1;} %%%% <<----- run over the previous value of y1
\draw[step=.5cm,gray,very thin] (-2.4,-2.4) grid (2.4,2.4);
\draw [-latex] (-2.5,0) -- (2.5,0);
\draw [-latex] (0,-2.5) -- (0,2.5);
\draw [thick, - latex] (0,0) -- (\x1,\y1);
\end{tikzpicture}
\end{document}
答案1
如果您在 tikzpicture 周围的组内进行定义,它将只定义该组内的变量。
您可以通过例如使用来明确添加一个组{...}
,或者您可以将您的定义放在 tikpicture 内,它会自动形成一个组。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{math}
\tikzmath{\x1 = 2; \y1=1;} %%%% <<----- First definition
\begin{document}
In this lecture we will talk about complex numbers.
The complex number $2+\mathrm{i}$ can be pictured in the following way:
{
\tikzmath{\x1 = 1;}
\begin{tikzpicture}
\draw[step=.5cm,gray,very thin] (-2.4,-2.4) grid (2.4,2.4);
\draw [-latex] (-2.5,0) -- (2.5,0);
\draw [-latex] (0,-2.5) -- (0,2.5);
\draw [thick, - latex] (0,0) -- (\x1,\y1);
\end{tikzpicture}
}
An example for a vector with a negative argument is the following:
\begin{tikzpicture}
\tikzmath{\y1=-1;} %%%% <<----- run over the previous value of y1
\draw[step=.5cm,gray,very thin] (-2.4,-2.4) grid (2.4,2.4);
\draw [-latex] (-2.5,0) -- (2.5,0);
\draw [-latex] (0,-2.5) -- (0,2.5);
\draw [thick, - latex] (0,0) -- (\x1,\y1);
\end{tikzpicture}
\end{document}