7

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?

13

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

6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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