使用 Tikz 在坐标平面上绘制垂直线

使用 Tikz 在坐标平面上绘制垂直线

我正在尝试使用 Tikz 环境绘制垂直线 x=0 和 x=4。到目前为止,我得到的是;

\begin{tikzpicture}[yscale=1] 
% 4x4 grid
\draw (0, 0) grid (5, 5);
% origin point
\draw [color=blue, fill=black] (0, 0) circle (0.1);
\draw [color=blue, fill=blue] (1, 1) circle (0.1);
\draw [color=blue, fill=blue] (2, 1) circle (0.1);
\draw [color=blue, fill=blue] (3, 1) circle (0.1);
\draw [color=blue, fill=blue] (1, 2) circle (0.1);
\draw [color=blue, fill=blue] (2, 2) circle (0.1);
\draw [color=blue, fill=blue] (3, 2) circle (0.1);
\draw [color=blue, fill=blue] (1, 2) circle (0.1);
\draw [color=blue, fill=blue] (1, 3) circle (0.1);
\draw [color=blue, fill=blue] (2, 3) circle (0.1);
\draw [color=blue, fill=blue] (3, 3) circle (0.1);
\node at (4,-.5) {$\frac{1}{2}$};
\node at (-.5,4) {$\frac{1}{2}$};
 % x-axis
\draw [thick,->] (0, 0) -- (5.5, 0);
 % y-axis
\draw [thick,->] (0, 0) -- (0, 5.5);
% origin label
\node at (-0.1, -0.5) {(0, 0)};
%Labeling of points
\node at (1.25, 3.25) {$P_{1}$};
\node at (2.25, 3.25) {$P_{2}$};
\node at (3.25, 3.25) {$P_{3}$};
\node at (1.25, 2.25) {$P_{4}$};
\node at (2.25, 2.25) {$P_{5}$};
\node at (3.25, 2.25) {$P_{6}$};
\node at (1.25, 1.25) {$P_{7}$};
\node at (2.25, 1.25) {$P_{8}$};
\node at (3.25, 1.25) {$P_{9}$};
\draw [green, thick, domain=0:4] plot (\x, {0});
\draw [green, thick, domain=0:4] plot (\x, {4});
% x-axis label
\node at (6, 0) {x};
% y-axis label
\node at (0, 6) {y};
\end{tikzpicture}

命令 plot (\x {0}) 和 plot (\x {4}) 生成线 y=0 和 y=4。我原以为命令 plot (\y {0}) 和 plot (\y {4} 会生成所需的线,但我只收到一个错误。有没有一种直接的方法来绘制这些线?

答案1

除了评论中提供的解决方案外,由于发现了重复模式,可以使用循环和调用标签下标的foreach计数器来简化代码。因此,这项技巧可以大大减少许多行编码。sub

在此处输入图片描述

代码

\documentclass{article}
\usepackage{tikz}
\begin{document}

New solution:

\begin{tikzpicture}[yscale=1] 
\newcounter{sub}
\setcounter{sub}{1}
\draw (0, 0) grid (5, 5);  % 4x4 grid
%  for each loop
\foreach \y in {3,2,1}{
\foreach \x in {1,2,3}{
\draw [color=blue, fill=blue] (\x, \y) circle (0.1);  % for the blue cicles
\node at (\x+0.25, \y+0.25) {$P_{\thesub}$};          % for the P_sub labels
\stepcounter{sub}
}}                                                    % what follows are OP's code mainly
\node at (4,-.5) {$\frac{1}{2}$};
\node at (-.5,4) {$\frac{1}{2}$};

\node at (-0.1, -0.5) {(0, 0)};% origin label
\draw [green, thick, domain=0:4] plot ({0},\x);
\draw [green, thick, domain=0:4] plot ({4},\x);

\node at (6, 0) {x};% x-axis label
\draw [thick,->] (0, 0) -- (5.5, 0);
\node at (0, 6) {y};% y-axis label
\draw [thick,->] (0, 0) -- (0, 5.5);
\draw [color=blue, fill=black] (0, 0) circle (0.1);
\end{tikzpicture}

\end{document}

相关内容