# I'm trying to graph a rational function in tikz [duplicate]

I'm attempting to graph the function y=[(x-2)(x+2)]/[(x-3)(x+3)]. However, I get bizarre output, which consists of straight lines. Any idea what's wrong?

Thanks!

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

\draw[gray,very thin] (-5,-5) grid (5,5);

\draw[black, very thick,<->](-5,0) -- (5,0);

\draw[black,very thick,<->](0,-5) -- (0,5);

\draw[very thick,domain=-5:-3.20156] plot ({\x},{((\x-2)(\x+2))/((\x-3)(\x+3))});

\draw[very thick,domain=-2.8577:2.8577] plot ({\x},{((\x-2)(\x+2))/((\x-3)(\x+3))});

\draw[very thick,domain=3.20156:5] plot ({\x},{((\x-2)(\x+2))/((\x-3)(\x+3))});

\end{tikzpicture}

\end{document}

• You get what you ask for, I think. What fixes the domains you're using?
– user121799
Nov 4 '18 at 16:03
• The domain is determined by the bounds -5<y<5. Nov 4 '18 at 16:06
• Yes, but you also forgot the multiplication signs.
– user121799
Nov 4 '18 at 16:08

You simply forgot multiplication signs and can make your life much more comfortable if you use declare function. And even even simpler with pgfplots because then you can just "jump" over singularities.

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}

\begin{document}
\begin{tikzpicture}[declare function={f(\x)=((\x-2)*(\x+2))/((\x-3)*(\x+3));},
samples=101]
\draw[gray,very thin] (-5,-5) grid (5,5);
\draw[black, very thick,<->](-5,0) -- (5,0);
\draw[black,very thick,<->](0,-5) -- (0,5);
\draw[very thick,domain=-5:-3.20156] plot ({\x},{f(\x)});
\draw[very thick,domain=-2.8577:2.8577] plot ({\x},{f(\x)});
\draw[very thick,domain=3.20156:5] plot ({\x},{f(\x)});
\end{tikzpicture}

\begin{tikzpicture}[declare function={f(\x)=((\x-2)*(\x+2))/((\x-3)*(\x+3));}]
\begin{axis}[grid=major,axis lines=middle,xtick=\empty,ytick=\empty,
unbounded coords=jump,samples=101]
\end{axis}
\end{tikzpicture}

\end{document}


run with xelatex

\documentclass{article}
\usepackage{pst-plot}
\begin{document}

\begin{pspicture*}[showgrid](-5,-5)(5,5)
\psaxes[labels=none,ticks=none,arrowscale=1.5]{<->}(0,0)(-5,-5)(5,5)
\psplot[algebraic,plotpoints=501,yMaxValue=5.5,
linewidth=1.5pt]{-5}{5}{(x-2)*(x+2)/((x-3)*(x+3))}
\end{pspicture*}

\end{document}