Tikz 轴标签 \foreach 循环

Tikz 轴标签 \foreach 循环

我想知道是否有更简单的方法来为我的图表构建轴。我也使用 \begin{axis} \end{axis} 来绘制图表,但我想知道是否有一行代码可以用来填充 x 轴和 y 轴上的每个刻度标记,而无需手动输入它们。这是我的代码:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{graphics}
\usepackage{graphicx}
\pgfplotsset{compat=1.16}
\usetikzlibrary{arrows.meta}

\begin{document}

\begin{tikzpicture}
\path (2.5,20.7) node {\footnotesize \(f(x)\)};

\begin{scope}[transform shape,shift ={(2,19.2)}]
\draw[step=1, color=gray] (-1.5,-0.5) grid (3.5,4.5);
\draw[line width=0.05cm,->,>=stealth] (-1.5,0) -- (3.5,0) node[anchor=north] {\footnotesize \(x\)};
\draw[line width=0.05cm,->,>=stealth] (0,-0.5) -- (0,4.5) node[anchor=east] {\footnotesize \(y\)};
\path (-0.15,-0.15) node {\footnotesize \(0\)};
\path (-1,-0.18) node {\footnotesize \(-1\)};
\path (1,-0.18) node {\footnotesize \(1\)};
\path (2,-0.18) node {\footnotesize \(2\)};
\path (3,-0.18) node {\footnotesize \(3\)};
\path (-0.18,1) node {\footnotesize \(1\)};
\path (-0.18,2) node {\footnotesize \(2\)};
\path (-0.18,3) node {\footnotesize \(3\)};
\path (-0.18,4) node {\footnotesize \(4\)};
\draw[blue, line width=0.4mm, samples=1000, domain=-1.1:3] plot (\x, {\x+2});
\draw[blue,fill=white](1,3) circle(.07);
\end{scope}
\end{tikzpicture}
\end{document}

任何帮助都将不胜感激。感谢您的时间,

缺口

答案1

在我看来,最简单的方法是使用以下两行:

\foreach \i in {-1,0,...,3}{node[below right] at (\i,0) {\footnotesize$\i$};
\foreach \i in {1,...,4}{node[above left] at (0,\i) {\footnotesize$\i$};

完整代码如下:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\begin{document}

\begin{tikzpicture}
\path (2.5,20.7) node {\footnotesize \(f(x)\)};

\begin{scope}[transform shape,shift ={(2,19.2)}]
\draw[step=1, color=gray] (-1.5,-0.5) grid (3.5,4.5);
\draw[line width=0.05cm,->,>=stealth] (-1.5,0) -- (3.5,0) node[anchor=north] {\footnotesize \(x\)};
\draw[line width=0.05cm,->,>=stealth] (0,-0.5) -- (0,4.5) node[anchor=east] {\footnotesize \(y\)};

\foreach \i in {-1,0,...,3}\node[below right] at (\i,0) {\footnotesize$\i$};
\foreach \i in {1,...,4}\node[above left] at (0,\i) {\footnotesize$\i$};
\draw[blue, line width=0.4mm, samples=1000, domain=-1.1:2.5] plot (\x, {\x+2});
\draw[blue,fill=white](1,3) circle(.07);
\end{scope}
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

带有pgfplots网格的标签是自动的。

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
%\usepackage{graphics}
%\usepackage{graphicx}
\pgfplotsset{compat=1.16}
\usetikzlibrary{arrows.meta}

\begin{document}
\begin{tikzpicture}
\begin{axis}[%
    x=1cm, y=1cm,
    axis lines=middle,
    xlabel=$x$, ylabel=$y$,
    xmin=-1.5, xmax=3.5,
    ymin=-0.5, ymax=4.5,
    grid=major,
]
\addplot[blue, domain=-1.1:3, line width=0.4mm] {x+2};
\addplot[blue, only marks, fill=white] coordinates {(1,3)};
\end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容