我想创建一个TikZ
创建坐标系的命令。到目前为止,我已经创建了这个 MWE:
\documentclass[12pt,a4paper, xcolor=dvipsnames]{scrartcl}
\PassOptionsToPackage{svgnames}{xcolor}
\usepackage{tikz}
\newcommand{\coordinatesystem}[4]{
\begin{tikzpicture}
\draw[step=1, gray!40] (#1,#2) grid (#3,#4);
\draw[-stealth,very thick] (#1,0) -- (#3,0);
\draw[-stealth,very thick] (0,#2) -- (0,#4);
\foreach \x in {#1,...,#3}
\foreach \y in {#2,...,#4}
{
\node[text=gray!30, below] at (\x,0) {$\x$};
\node[text=gray!30, left] at (0,\y) {$\y$};
}
\end{tikzpicture}
}
\begin{document}
\coordinatesystem{-5}{-5}{3}{4}
\end{document}
我希望 x 轴节点稍微向右移动一点,以避免与坐标系线发生碰撞。同样,我希望 y 轴节点比现在稍微高一点。这可能吗?
答案1
如果您不想在 xy 刻度上打印零,请修改您的代码如下:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage{tikz}
\newcommand{\coordinatesystem}[4]{
\begin{tikzpicture}
\draw[step=1, gray!40] (#1,#2) grid (#3,#4);
\draw[-stealth,very thick] (#1,0) -- (#3,0);
\draw[-stealth,very thick] (0,#2) -- (0,#4);
\foreach \x in {#1,...,#3}
\foreach \y in {#2,...,#4}
{
\ifnum \x=0
\relax%
\else %
{\node[text=gray!30, below] at (\x,0) {$\x$};}
\fi
\ifnum \y=0
\relax%
\else %
{\node[text=gray!30, left] at (0,\y) {$\y$};}
\fi
}
\node[text=gray!30] at (-.3,-.3) {$O$};
\end{tikzpicture}
}
\begin{document}
\noindent
\coordinatesystem{-5}{-5}{3}{4}\,
\coordinatesystem{-4}{-5}{4}{4}
\end{document}
输出:
添加:无论如何,单靠坐标系是无用的。上面的答案无法放置任何图形或图表。因此,您需要在 \newcommand 定义之外添加\begin{tikzpicture}
and \end{tikzpicture}
,例如,如下所示:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage{tikz}
\newcommand{\coordinatesystem}[4]{
\draw[step=1, gray!40] (#1,#2) grid (#3,#4);
\draw[-stealth,very thick] (#1,0) -- (#3,0);
\draw[-stealth,very thick] (0,#2) -- (0,#4);
\foreach \x in {#1,...,#3}
\foreach \y in {#2,...,#4}
{
\ifnum \x=0
\relax%
\else %
{\node[text=gray!30, below] at (\x,0) {$\x$};}
\fi
\ifnum \y=0
\relax%
\else %
{\node[text=gray!30, left] at (0,\y) {$\y$};}
\fi
}
\node[text=gray!30] at (-.3,-.3) {$O$};
}
\begin{document}
\noindent
\begin{tikzpicture}
\coordinatesystem{-4}{-5}{4}{4}
\clip (-4,-5) rectangle (4,4);
\draw[cyan,line width=2pt] plot[domain=-4:4] (\x,-\x-1);
\draw[magenta,line width=2pt] plot[domain=-4:4,smooth] (\x,\x*\x-4);
\end{tikzpicture}
\end{document}
使用上述代码,您将获得以下输出: