在多个位置插入 tikzpicture

在多个位置插入 tikzpicture

我是 Latex 和 tikzpicture 的新手。我有一段代码如下:

\begin{tikzpicture}

% horizontal axis
\draw[->] (0,0) -- (10,0) node[anchor=north] {$z$};

% labels
\draw   (0,0) node[anchor=north] {0}
    (2,0) node[anchor=north] {20}
    (2.5,0) node[anchor=north] {25}
    (8,0) node[anchor=north] {80}
    (8.5,0) node[anchor=north] {85};

 % vertical axis
\draw[->] (0,0) -- (0,3) node[anchor=east] {$K$};
\draw   (0,0) node[anchor=east] {0}
    (0,2) node[anchor=east] {1};

\draw[thick] (2,0) -- (2.5,2) -- (8,2) -- (8.5,0);

\draw[thick,dashed] (2.5,0) -- (2.5,2);
\draw[thick,dashed] (8.,0) -- (8.0,2);


\end{tikzpicture}

我想在文档的多个位置使用上面的图片。如何在主代码中引用此图片。像这样:

%% Call the above picture at coordinate (6,0)

%%% Some text %%%%

%% call the above picture at coordinate (12,-3) and (12, -9)

如何做这样的事情?任何帮助都将不胜感激。

谢谢

答案1

你可以使用类似 的样式定义一个新的图片mydrawing/.pic={...}。然后像 一样使用它node。以下是具体的例子:

\documentclass[tikz,border=7pt]{standalone}
\tikzset{
  mydrawing/.pic = {
    % horizontal axis
    \draw[->] (0,0) -- (10,0) node[anchor=north] {$z$};
    % labels
    \draw
        (0,0) node[anchor=north] {0}
        (2,0) node[anchor=north] {20}
        (2.5,0) node[anchor=north] {25}
        (8,0) node[anchor=north] {80}
        (8.5,0) node[anchor=north] {85};
     % vertical axis
    \draw[->] (0,0) -- (0,3) node[anchor=east] {$K$};
    \draw
      (0,0) node[anchor=east] {0}
      (0,2) node[anchor=east] {1};
    \draw[thick] (2,0) -- (2.5,2) -- (8,2) -- (8.5,0);
    \draw[thick,dashed] (2.5,0) -- (2.5,2);
    \draw[thick,dashed] (8.,0) -- (8.0,2);
  }
}

\begin{document}
  \begin{tikzpicture}
    \pic at (0,0) {mydrawing};
    \pic[scale=0.7] at (12,-3) {mydrawing};
    \pic[red] at (12,-9) {mydrawing};
  \end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

只需放入所有\newcommand绘图部分:

\documentclass[landscape]{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand\mypic[1]{
% horizontal axis
\draw[->] #1 -- ($#1+(10,0)$) node[anchor=north] {$z$};

% labels
\draw   #1 node[anchor=north] {0}
    ($#1+(2,0)$) node[anchor=north] {20}
    ($#1+(2.5,0)$) node[anchor=north] {25}
    ($#1+(8,0)$) node[anchor=north] {80}
    ($#1+(8.5,0)$) node[anchor=north] {85};

 % vertical axis
\draw[->] ($#1+(0,0)$) -- ($#1+(0,3)$) node[anchor=east] {$K$};
\draw   #1 node[anchor=east] {0}
    ($#1+(0,2)$) node[anchor=east] {1};

\draw[thick] ($#1+(2,0)$) -- ($#1+(2.5,2)$) -- ($#1+(8,2)$) -- ($#1+(8.5,0)$);

\draw[thick,dashed] ($#1+(2.5,0)$) -- ($#1+(2.5,2)$);
\draw[thick,dashed] ($#1+(8.,0)$) -- ($#1+(8.0,2)$);
}

\begin{document}
\noindent\begin{tikzpicture}[scale=0.7]
\mypic{(0,0)}
\mypic{(12,-3)}
\mypic{(12,-9)}
\end{tikzpicture}
\end{document}

输出:

在此处输入图片描述

嵌套的 tikzpictures 并不真正可取,因此我将\beginand排除\end{tikzpicture}在命令之外

我还必须在calc库的帮助下使用“相对坐标”。

相关内容