[Tex/LaTex] How to make a graph of a function

diagrams

I'm trying to implement a function to LaTeX but i don't know how. I'm compiling using this page: docs.latexlab.org

Best Answer

Compile the following code with xelatex or a combo sequence latex-dvips-ps2pdf.

enter image description here

\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pst-plot}

\begin{document}
\begin{pspicture}(-4.25,-1.25)(4.25,2.25)
    \def\f(#1){sin(2*#1)+0.5}
    \psaxes[labelFontSize=\scriptscriptstyle,ticksize=-2pt 2pt]{->}(0,0)(-4,-1)(4,2)[$x$,0][$y$,90]
    \psplot[linecolor=blue,algebraic]{-\psPi}{\psPi}{\f(x)}
    \rput[tl](*1 {\f(x)+0.5}){$y=\sin(2x)+\frac{1}{2}$}
\end{pspicture}
\end{document}

Explanation

  1. Making diagrams (including function plotting) can be accomplished by using PSTricks (recommended because it is faster and easier to learn yet powerful) or TikZ or others. The code above is written in PSTricks, you need to load \usepackage{pst-plot}.
  2. To get a tight page, use

    \documentclass[pstricks,border=12pt]{standalone}
    
  3. Define a canvas on which you draw.

    \begin{pspicture}(-4.25,-1.25)(4.25,2.25)
     ... drawing codes go here ...
    \end{pspicture}
    

    (-4.25,-1.25) represents the bottom left point of your canvas and (4.25,2.25) is the top right point.

  4. Define the function to plot.

    \def\f(#1){sin(2*#1)+0.5}
    

    In this example I chose y=sin(2x)+1/2.

  5. Draw the coordinate axes.

    \psaxes[labelFontSize=\scriptscriptstyle,ticksize=-2pt 2pt]{->}(0,0)(-4,-1)(4,2)[$x$,0][$y$,90]
    
  6. Plot the graph.

    \psplot[linecolor=blue,algebraic]{-\psPi}{\psPi}{\f(x)}
    
  7. Put a label if necessary.

     \rput[tl](*1 {\f(x)+0.5}){$y=\sin(2x)+\frac{1}{2}$}
    

    In PSTricks, we can specify a point in several ways. (*<x-value> {the value of expression in x for the given x}) is one of them. Thus (*1 {\f(x)+0.5}) mathematically means a point (x,y) where x=1 and y=f(1)+0.5.

  8. Compile the input file with xelatex or the combo sequence latex-dvips-ps2pdf.

  9. Done!

Miscellaneous

\psplot[linecolor=blue,algebraic,plotpoints=100]{Pi neg .5 sub}{Pi .5 add}{\f(x)}
  • The plotpoints can be used to increase the number of points used to plot the graph. But be wise, the greater its value is, the smoother the plot is but the bigger the file size becomes. For most extreme case, plotpoints=1000 should be more than enough.

  • The first and second arguments of \psplot can accept RPN notation. In the example above, I used -π-.5 and π+.5 for both args, respectively. PSTricks gives you many good features, right?

Related Question