1

I've spent all day on this and have found no solution; I'm trying to graph a cosine plot (y(x) = 2cos(x/4)) and while I have tried to plot the actual function out on pgfplot, the graph just wouldn't work, with either the negative values going on the positive side, or the curves not showing up at all so I decided to just plot the coordinates instead which has technically almost worked.

The problem is that my coordinates are pi values but they don't show up as such in the plot and I've tried xticklabels but that isn't working either.

This is my code:

\begin{tikzpicture}
\begin{axis}
   [grid=both,
minor tick num=4,
grid style={line width=.2pt, draw=black!10},
major grid style={line width=.4pt,draw=black!50},
axis lines=middle,
enlargelimits={abs=0.1},
width=12cm, height=9cm
]
axis y line=middle,
axis x line=middle,
\addplot[smooth, blue] coordinates {
    (-6*pi,  0)
    (-4*pi,  -2)
    (-2*pi,  0)
    (0, 2)
    (2*pi, 0)
    (4*pi, -2)
    (6*pi, 0)
};
\end{axis}
\end{tikzpicture}

And this is the picture: cosine

What I'm trying to figure out is how to change the values on the x-axis to pi while keeping those on the y-axis as they are.

Thanks!

1 Answers1

1

xticklabels does work if done right. I don't know what you tried, but the following is one example.

Regarding plotting the function, I again don't know what you did, but one thing to take into account with trigonometric functions is that they assume degrees as input, so if you have radians you need to convert to degrees e.g. with deg(..), or add trig format=rad to the axis options.

enter image description here

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
  grid=both,
  minor tick num=4,
  grid style={
     line width=.2pt, draw=black!10
  },
  major grid style={
    line width=.4pt,draw=black!50
  },
  axis lines=middle,
  enlargelimits={abs=0.1},
  width=12cm, height=9cm,
  xtick={-6*pi,-4*pi,...,6*pi},
  xticklabels={$-6\pi$,$-4\pi$,$-2\pi$,,$2\pi$,$4\pi$,$6\pi$}
]

\addplot[smooth, blue,domain=-6pi:6pi] {2*cos(deg(x/4)))}; \end{axis} \end{tikzpicture} \end{document}

Torbjørn T.
  • 206,688
  • Instead of the explicit ticklabels its also possible to define the "format" of the labels, with xticklabel={\pgfmathparse{\tick/pi}$\pgfmathprintnumber[precision=0]{\pgfmathresult}\pi$} – Torbjørn T. Jun 20 '20 at 22:27