我想\draw (0,0) grid[xstep=1,ystep=1] (5,5)
在轴环境中这样做,但除非 xmin(和 ymin)为零,否则输出不会如预期。如何为这三个示例绘制 xstep 为 1 的网格?
注意:我想使用 \draw 中的网格命令,而不是 \axis 的网格选项或使用 \foreach 绘图。
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=-1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=-1$},
]
\draw (0,0) grid[xstep=1,ystep=1] (5,5);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=0, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=0$},
]
\draw (0,0) grid[xstep=1,ystep=1] (5,5);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=1$},
]
\draw (0,0) grid[xstep=1,ystep=1] (5,5);
\end{axis}
\end{tikzpicture}
% This works as expected.
\newcommand{\DrawGrid}{
\draw\foreach\k in {0,1,...,5} {(\k,0) -- (\k,5) (0,\k) -- (5,\k)};
}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=-1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=-1$},
]
\DrawGrid
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=0, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=0$},
]
\DrawGrid
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=1$},
]
\DrawGrid
\end{axis}
\end{tikzpicture}
\end{document}
答案1
使用pgfplots step
来自我的答案似乎按预期工作。
代码
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\tikzset{pgfplots step/.style args={#1 by #2}{step={(axis direction cs:#1,#2)}}}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=-1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=-1$}]
\draw (0,0) grid[pgfplots step=1 by 1] (5,5);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=0, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=0$}]
\draw (0,0) grid[pgfplots step=1 by 1] (5,5);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=1$}]
\draw (0,0) grid[pgfplots step=1 by 1] (5,5);
\end{axis}
\end{tikzpicture}
% This works as expected.
\newcommand{\DrawGrid}{
\draw\foreach\k in {0,1,...,5} {(\k,0) -- (\k,5) (0,\k) -- (5,\k)};
}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=-1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=-1$}]
\DrawGrid
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=0, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=0$}]
\DrawGrid
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
width=12em, height=12em, xmin=1, xmax=7, ymin=0, ymax=7,
xlabel={$x_\mathrm{min}=1$}]
\DrawGrid
\end{axis}
\end{tikzpicture}
\end{document}