6

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: 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}
4

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.

enter image description here

\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$,
  domain=-pi:pi,samples=101, % added
]

\addplot [blue,thick] {func(x)};
\end{axis}
\end{tikzpicture} 
\end{document}
  • Do ask if anything is unclear. – Torbjørn T. Jun 6 '17 at 9:02
  • That makes sense, and I understand the logic behind the syntax. Just one last question; If I wanted more of the function to be drawn, how would I specify that? – Hatze Jun 6 '17 at 9:11
  • @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
  • Okay, I understand. I thank you very much for your help! – Hatze Jun 6 '17 at 9:18
  • x >= -pi/2 should be replaced by \x >= -pi/2 – Black Mild Nov 11 '18 at 3:58

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.