# Plotting a piecewise function

I'm trying to learn to plot in latex, but I'm having a problem trying to find out which packages that are best to use in this situation, and I find it a bit of a learning curve.

Suppose you have the following function: I would like to know, how I could graph this in Latex. I have searched around and found out that you could use the PGF and tikz packages, and use the declare function, but I have problems with the intervals in which $x$ is defined

How would I approach this problem, as a complete newbie to graphing in Latex? I tried using a similiar post about it, and tried to plug in my intervals. My code looks like this:

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
%\pgfplotsset{compat=1.8}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x \in [-\pi, -\frac{pi}{2}) * (0)   +
and(\x \in [-\frac{\pi}{2},\frac{\pi}{2}) * (\frac{\pi}{2}-|x|)     +
and(\x \in [\frac{\pi}{2}, \pi]) * (0)
;
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=-5, ymax=5, ytick={-5,...,5}, ylabel=$y$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$x$,
]
\end{axis}
\end{tikzpicture}
\end{document}

• Hi, welcome. Can you show us what you've tried? – Torbjørn T. Jun 6 '17 at 8:25
• Hi. I found a similiar post, and tried to just plug in the intervals, but it doesn't seem to work. – Hatze Jun 6 '17 at 8:39
• – Ignasi Jun 6 '17 at 8:40
• Which post? Please add the code you have so far to your question. – Torbjørn T. Jun 6 '17 at 8:40
• I added the code I tried. It just gives me a blank graph. – Hatze Jun 6 '17 at 8:46

There are a couple of things you've gotten wrong. First of all, as marsupilam says in a comment, you have to plot the function as well, not just declare it.

Second, you can't use \frac, \pi etc. when declaring functions. They are macros intended for typesetting math, to do a calculation write it like e.g. pi/2. \documentclass[tikz]{standalone}
\usepackage{pgfplots}
%\pgfplotsset{compat=1.8}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x < -pi/2) * (0)   +
and(\x >= -pi/2, \x < pi/2) * (pi/2-abs(\x))     +
(\x >= pi/2) * (0)
;
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=-5, ymax=5, ytick={-5,...,5}, ylabel=$y$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$x$,

• @Hatze The domain setting defines the domain over which to plot the function, if that is what you meant. – Torbjørn T. Jun 6 '17 at 9:13