2

This question already has an answer here:

I have two problems when trying to add the value of a data point above the data point. I am trying to solve this with a for-loop:

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}

\begin{tikzpicture}
\def \myvalues{{50,50,31,25,24,24,24,24,24,24,24,24,24,24,24}}%


\begin{axis}[
    width=\textwidth,
    height=.40\textwidth,
    xlabel={x},
    ylabel={y},
    xtick={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},
    ytick={20,25,30,35,40,45,50},
    xmajorgrids,
    ymajorgrids,
]
\addplot [black, mark=*, mark options={solid}]
table {%
1 50
2 50
3 31
4 25
5 24
6 24
7 24
8 24
9 24
10 24
11 24
12 24
13 24
14 24
15 24
};

 \pgfplotsinvokeforeach{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}{
        \pgfmathparse{\myvalues[#1-1]};
    \node at (#1,\pgfmathresult+2){\pgfmathresult};
    }

\end{axis}


\end{tikzpicture}
\end{document}

Problems:

  • Document compiles without errors, but the nodes don't show up in the plot.
  • How can I add an if-statement into the for-loop? For example to change the color of the node to red for the nodes 4 and 12?

Thanks a lot! -

marked as duplicate by Stefan Pinnow, egreg tikz-pgf Mar 2 '17 at 14:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    You could have a look at nodes near coords. Add nodes near coords right after ymajorgrids, in the axis options and the first point is taken care of. – Torbjørn T. Mar 2 '17 at 12:15
1

Check out this answer for another question (among others).

Summarised: pgfplots does not execute the command at the time you think it does, but postpones it. At that point \pgfmathresult does not contain the computation result any more. You can, however, force the expansion by defining a temporary macro. Note then in this case, any tikz command (\node, \fill, \draw, ...) will need to be protected by a \noexpand.

The following code works:

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}

\begin{tikzpicture}
\def \myvalues{{50,50,31,25,24,24,24,24,24,24,24,24,24,24,24}}%


\begin{axis}[
    width=\textwidth,
    height=.40\textwidth,
    xlabel={x},
    ylabel={y},
    xtick={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},
    ytick={20,25,30,35,40,45,50},
    xmajorgrids,
    ymajorgrids,
]
\addplot [black, mark=*, mark options={solid}]
table {%
1 50
2 50
3 31
4 25
5 24
6 24
7 24
8 24
9 24
10 24
11 24
12 24
13 24
14 24
15 24
};

 \pgfplotsinvokeforeach{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}{
        \pgfmathparse{\myvalues[#1-1]};
        \edef\temp{
            \noexpand\node at (#1,\pgfmathresult+2){\pgfmathresult};
        }
        \temp
    }

\end{axis}


\end{tikzpicture}
\end{document}

Not the answer you're looking for? Browse other questions tagged or ask your own question.