0

I'm trying to construct a plot using pgfplots in which I perform \draw commands using axis cs. Additionally, the coordinates of axis cs are assigned to the result of a math expression using an iterator generated with a foreach loop. Here's the code I've got:

\begin{tikzpicture}
  \begin{axis}[
  title=Sinusoid Sampled Values (1 Period),
  xlabel={$t$},
  ylabel={$A$},
  axis x line=middle,
  axis y line=left,
  xmin=0, xmax=2*pi,
  ymin=-1, ymax=1,
]
  \foreach \x in {0,1,...,15} {
    \draw (axis cs:\pgfmathparse{2*pi*\x/16}\pgfmathresult,0)
      -- (axis cs:\pgfmathparse{2*pi*\x/16}\pgfmathresult,\pgfmathparse{sin(2*pi*\x/16)}\pgfmathresult)
      circle[radius=2];
  }
\end{axis}
\end{tikzpicture}

However, this fails I'm unsure which part of the process is creating the issue. I suspect it's pgfmathparse, but maybe it's the loop? How can I achieve the desired result here? Let me know if you need any further info.

1

You could use pgfplots-internal commands to achieve (probably) the same:

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
        title=Sinusoid Sampled Values (1 Period),
        xlabel={$t$},
        ylabel={$A$},
        axis x line=middle,
        axis y line=left,
        xmin=0, xmax=2*pi,
        ymin=-1, ymax=1,
    ]

    \addplot[ycomb, domain=0:15, samples=16, mark=*] (2*pi*x/16, {sin(2*pi*x/16 r)});
    \end{axis}
    \end{tikzpicture}  
\end{document}

Note: as pgf expects degree in trigonometric functions, I added the r to convert it to radians. enter image description here

Another (even easier) solution:

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[
        title=Sinusoid Sampled Values (1 Period),
        xlabel={$t$},
        ylabel={$A$},
        axis x line=middle,
        axis y line=left,
        xmin=0, xmax=2*pi,
        ymin=-1, ymax=1,
        xtick={0, pi/2, pi, 3*pi/2, 2*pi},
        xticklabels={0, $\frac{\pi}{2}$,  $\pi$, $\frac{3}{2}\pi$, $2\pi$}
    ]

    \addplot expression[ycomb, domain=0:{30/16*pi}, samples=16, mark=o] {sin(\x r)};
    \end{axis}
    \end{tikzpicture}  
\end{document}

enter image description here

| improve this answer | |

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.