Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am trying to plot the function 1/x^2 but the result is obviously wrong, here is how it looks like

enter image description here

here is the code

\begin{center} 
    \begin{tikzpicture}
     \begin{axis}[ 
    %xlabel=$x$,
    %ylabel={$f(x) = x^2 - x +4$}   ] 
    \addplot[blue] {1/(x^2)};
    \end{axis}
    \end{tikzpicture}
\end{center}

Any suggestions on how to fix this?

share|improve this question

2 Answers 2

up vote 13 down vote accepted

You're dividing by nearly zero, so that result is in a way expected. You could use restrict y to domain=0:20 to remove all y-values larger than 20, or (easier) just add ymax=25 to set the maximum value for the y-axis.

The difference between the two is that the former removes all calculated y-values that are outside the given domain from the plot, while the second just sets the axis limits. With the latter, the lines will extend to the axis.

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[ 
    xlabel=$x$,
    ylabel={$f(x) = 1/x^2$},
    restrict y to domain=0:20,
    ] 
\addplot[blue,samples=200] {1/(x^2)};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[ 
    xlabel=$x$,
    ylabel={$f(x) = 1/x^2$},
    ymax=20
    ] 
\addplot[blue,samples=200] {1/(x^2)};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

share|improve this answer
    
brilliant thanks! –  Mohamed Ali Jamaoui Apr 20 at 17:11

This works fine.....

\documentclass[a4paper]{article}
\usepackage{tkz-euclide}
\usepackage{pgfplots}
\usetkzobj{all}
\begin{document}
\begin{center}
\begin{tikzpicture}
\begin{axis}%
    [
        grid=major,  
        x=5mm,
        y=5mm,
        xtick={-10,-9,...,10},   
        xmin=-10,
        xmax=10,
        xlabel={\tiny $x$},
        axis x line=middle,
        ytick={-10,-9,...,10},
        tick label style={font=\tiny},
        ymin=-10,
        ymax=10,
        ylabel={\scriptsize $f(x)$},
        axis y line=middle,
        no markers,
        samples=100,
        domain=-10:10,
        restrict y to domain=-20:20
    ]
    \addplot[thick,samples=400] (x,{1/x^2});
\end{axis} 
\end{tikzpicture}
\end{center}
\end{document}

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.