# Graphing truncated Fourier transform

I need to graph the following three figures that represent the truncated Fourier series.

I really have no idea how to graph them. Can anyone help me please?

## 2 Answers

\documentclass[border = 5pt]{standalone}

\usepackage{pgfplots}
\usepackage{ifthen}
\pgfplotsset{compat=1.14}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
xmin = 0, xmax = 2.5 * pi,
ymin = -0.2, ymax = 1.2,
domain = 0 : 2 * pi,
xlabel = $x$,
ylabel = $y$,
axis x line = center,
axis y line = center,
every axis x label/.append style = {below},
every axis y label/.append style = {left},
samples = 100,
xtick = {0, 3.14, 6.28},
xticklabels = {$0$, $\pi$, $2\pi$},
declare function = {
s(\x) = ifthenelse(\x < pi, 1, 0);
s0(\x) = 0.5 + (2 / pi) * sin(deg(\x);
s1(\x) = s0(\x) + (2 / pi) * sin(3 * deg(\x)) / 3.0));
s2(\x) = s1(\x) + (2 / pi) * sin(5 * deg(\x)) / 5.0));
s3(\x) = s1(\x) + (2 / pi) * sin(7 * deg(\x)) / 7.0));
}, ]
\addplot[ultra thick, black] {s(x)};
\addplot[thick, blue] {s0(x)};
\addplot[thick, red] {s1(x)};
\addplot[thick, orange] {s2(x)};
\addplot[thick, cyan] {s3(x)};
\legend{signal, $s_0$, $s_1$, $s_2$, $s_3$};
% labels
\draw[gray, dashed] (0, 0.5) -- (2 * pi, 0.5);
\draw[gray, dashed] (2 * pi, 0) -- (2 * pi, 1);
\end{axis}
\end{tikzpicture}

\end{document}


This code based on this post should give you a starting point.

\documentclass[tikz,border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}
\usepgfplotslibrary{colorbrewer}
\pgfplotsset{cycle list/Reds-6}

\begin{document}

\begin{tikzpicture}
\begin{axis}[%
width=\textwidth,
axis x line=bottom,
axis y line=left,cycle multi list={Reds-6}]
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5 + sin(4*5.5*\x r)/5.5};
\end{axis}
\end{tikzpicture}
\end{document}


EDIT

As I was not totally happy with my initial solution, please refer to this post to get some ways to avoid the cumbersome repetition of sums.

• +1 for colorbrewer that I didn't know May 1 '18 at 13:39
• @giusva To me it's the best colormap library ever ! And super well documented May 1 '18 at 13:43
• Definitely better than using xcolor to define each color and manually assign to each line. May 1 '18 at 13:52