每次我需要绘制一个简单的函数(例如抛物线)时,我都会使用一个自制的 TikZ 模板:
\documentclass{minimal}
\usepackage{pgfplots}
\pgfplotsset{/pgf/number format/use comma,compat=newest}
\pagestyle{empty}
\newcommand{\mygrid}{\draw [color=lightgray,dash pattern=on 2pt off 2pt,xstep=1.0cm,ystep=1.0cm] (-4.5,-4.5) grid (4.5,4.5);}
\newcommand{\Xaxis}{ \draw [->] (-4.5,0) -- (4.5,0) node [above] {$x$};\foreach \x in {-4,-3,-2,-1,1,2,3,4}\draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {$\scriptstyle\x$};}
\newcommand{\Yaxis}{ \draw [->] (0,-4.5) -- (0,4.5) node [left] {$y$};\foreach \y in {-4,-3,-2,-1,1,2,3,4}\draw[shift={(0,\y)},color=black] (2pt,0pt) -- (-2pt,0pt) node[left] {$\scriptstyle\y$};}
\begin{document}
\begin{tikzpicture}[>=latex]
\mygrid
\Xaxis
\Yaxis
\clip(-4.5,-4.5) rectangle (4.5,4.5);
\draw [very thick,blue,smooth,domain=-4.5:4.5] plot (\x,{(\x)^2-2*\x-3});
\end{tikzpicture}
\end{document}
如您所见,图形的绘制和裁剪范围是 x 轴和 y 轴的 -4.5 到 4.5。
如果我需要扩大或缩小绘图范围,我必须手动操作。有没有比“查找和替换”更简单的方法?
我有个主意:
\newcommand{\myplot}[2]{\mygrid\Xaxis\Yaxis}
但我知道我\foreach
肯定会在副本中遇到麻烦。
答案1
我建议使用 PGFPlots 包(您已经加载了)。它使代码更易于维护:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis equal image,
max space between ticks=20, % This is one way of getting a tick for every integer
ticklabel style={font=\scriptsize},
axis lines = middle,
xmin=-4.5, xmax=4.5, % The range over which the x axis is drawn
ymin=-4.5, ymax=4.5, % The range over which the y axis is drawn
domain=-4:4, % The range over which the function is evaluated
grid=both,
xlabel=$x$, ylabel=$y$
]
\addplot [very thick, blue, smooth] {x^2-2*x-3};
\end{axis}
\end{tikzpicture}
\end{document}