命令输入一组坐标并绘制它们

命令输入一组坐标并绘制它们

下面给出的是我用来绘制信号图的代码。

\documentclass[tikz]{standalone}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{figure}
{\tikz{%
\draw[thick, -Latex] ({-4-1.5},0) -- ({4+1.5},0);
\draw[thick, -Latex] (0,-4) node[below] {} -- (0,1) node[right] {$-3+x(t)$};
\node[anchor=north west] at (0,0){Time, $t \rightarrow$};
\draw [thick](-4,-3) node[below right]{$-3$}  -- (-2,-3) node[below right]{} |- (-2,-1) --(0,-1) node[below left] {$-1$}--(2,-1) -|(2,-3) node[below left] {$$} -- (4,-3)node[below left] {$$};
    }
  }
\end{figure}
\end{document}

由于我需要绘制更多,有什么方法可以只输入坐标 (x1,y1),(x2,y2)....(xn,yn) 并让 tikz 将它们连接起来吗?我还需要指定轴标签。例如,我可以定义一个命令(例如 \sigplot)或样式,以便我只需输入

\sigplot{-3+x(t)}{(-4,0),(-2,0),(-2,1),(2,1),(2,0),(4,0)} 
% the number of points might vary

并得到相同的结果?PS 我对 tikz 的了解很浅显。如果有人能帮我解释一下,我将不胜感激

答案1

如果您可以删除中间的逗号,那就很容易了。

\documentclass[tikz]{standalone}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{tikzpicture}
\def\sigplot#1#2{%
\draw[thick, -Latex] ({-4-1.5},0) -- ({4+1.5},0);
\draw[thick, -Latex] (0,-4) node[below] {} -- (0,1) node[right] {#1};
\node[anchor=north west] at (0,0){Time, $t \rightarrow$};
\draw plot coordinates {#2};
 }
\sigplot{$-3+x(t)$}{(-4,0) (-2,0) (-2,1) (2,1) (2,0) (4,0)} 
\end{tikzpicture}
\end{document}

但 pgfplots 可以做到这一切,甚至更多

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines*=center]
\addplot+[] coordinates {(-4,0) (-2,0) (-2,1) (2,1) (2,0) (4,0)} ;
\end{axis}
\end{tikzpicture}
\end{document}

答案2

试试这个(没有文字)

在此处输入图片描述

\documentclass{article}

\usepackage{tikz}

 \newcommand{\sigplot}[2]{
 \draw[thick, ->] ({-4-1.5},0) -- ({4+1.5},0);
\draw[thick, ->] (0,-4) node[below] {} -- (0,1) node[right] {$#1$};
\node[anchor=north west] at (0,0){Time, $t \rightarrow$};
 \newcommand*{\lastcoord}{}
 \foreach \coord [remember=\coord as \lastcoord]  in {#2}{
\draw \lastcoord -- \coord;
 };
}
\begin{document}

\begin{tikzpicture}
 \sigplot{-3+x(t)}{(-4,-3),(-2,-3),(-2,-1),(0,-1),(2,-1),(2,-3),(4,-3)}
\end{tikzpicture}  

\end{document}

相关内容