# Loop in PGFPlot axis environment / Adding value above data points [duplicate]

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}
\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,
]
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 StackExchange.ready(function() { if (StackExchange.options.isMobile) return; $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() { var$hover = $(this).addClass('hover-bound'),$msg = $hover.siblings('.dupe-hammer-message');$hover.hover( function() { $hover.showInfoMessage('', { messageElement:$msg.clone().show(), transient: false, position: { my: 'bottom left', at: 'top center', offsetTop: -7 }, dismissable: false, relativeToBody: true }); }, function() { StackExchange.helpers.removeMessages(); } ); }); }); Mar 2 '17 at 14:05

• 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

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}
\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,
]
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}