# Sine function in pgfplots and MATLAB. Why are different results obtained?

I did the graph (view image) of the absolute value of sine function in pgfplots and MATLAB. Why are different results obtained?

pgfplots:

\begin{tikzpicture}[scale=1.2]

\begin{axis}[
domain = 0:2*pi,
yticklabels={-2,-1,0,1,2},
axis lines = middle,
axis on top = true,
grid = major,
grid style = {dashed, line width=.1pt, draw=gray!30, /pgfplots/on layer=axis background},

]

\end{axis}


\end{tikzpicture}

strong text

MATLAB:

x = 0:0.01:2*pi;
y = sin(x);
z = abs(y);

plot(x,z,...
'LineWidth',1,...
'Color','blue');

• Because pgfplots has a default number of samples within the given domain, and that is set to 25. So you don't get a value at the middle minimum. Set samples=200 or something. – Torbjørn T. Mar 21 '17 at 19:03
• Also the y tick labels are wrong. You set the labels without setting the values, so you have for example label 0 on value 0.2... and so on. – Rmano Mar 21 '17 at 19:38
• Isn't this question exactly the same as tex.stackexchange.com/questions/357931? – Symbol 1 Mar 21 '17 at 20:37

You need to use more samples to make sure that pi is one of the x-values used to calculate the y-values.

The number of samples can be set using an optional argument to the \begin{axis} command.

\begin{axis}[samples=1000,...]

• As I supposed, i had to expand the domain. Ty Anders. – LuisPac Mar 21 '17 at 19:12

There are a couple of problems here.

First off, the number of sample is too small by default for your case --- you should ask for more, and, if you want to get the value in the middle of the domain, use an odd number of them.

samples = 101,


Then, you use xticklabels which puts the given labels at the (automatically calculated) ticks position... you should almost never use xticklabels without an explicit xtick. In this case, they are not needed.

Additionally (but this is a matter of style) I think that the graph is better with a bit of breathing, and indicating the coordinates (0,0); both effects are achieved removing axis lines = middle. So:

\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}\pgfplotsset{compat=1.13}
\usetikzlibrary{arrows.meta,positioning,calc}
\begin{document}
\begin{tikzpicture}[]
\begin{axis}[
domain = 0:2*pi,
samples = 101,
axis on top = true,
grid = major,
grid style = {dashed, line width=.1pt, draw=gray!30,
/pgfplots/on layer=axis background},
]
\end{axis}
\end{tikzpicture}
\end{document}


...and to show the xticklabels thing, if you add:

xtick = {0, 1.5708, ..., 7},
xticklabels = {$0\mathstrut$, $\pi/2$, $\pi\mathstrut$, $3\pi/2$, $2\pi\mathstrut$},


you have:

• Note: it's axis x line (not lines) – Mace Mar 22 '17 at 9:05