[Tex/LaTex] Naming the nodes of `nodes near coords` for later use

nodes-near-coordspgfplotstikz-pgf

I would like to use pgfplots command nodes near coords to get a
list of named node ((no1), (no2), (no3) etc.) that I can use
afterwards to draw some paths that I fail to construct with pgfplots
only.

I suppose it would need to use scatter/@post marker code but I did
not understand very well that part of the manual (p. 82).
Actually, if nodes near coords is a redefinition of scatter/@pre
marker code
so I suppose I don't really need nodes near coords and
could use a altered scatter.
I did not find however the code defining nodes near cords in the
manual and got lost into the huge code files of pgfplots.

Here is an example taken from the pgfplots manual that could
constitute a minimum example:

\begin{tikzpicture}
\begin{axis}[nodes near coords]
\addplot+[only marks] coordinates {
(0.5,0.2) (0.2,0.1) (0.7,0.6)
(0.35,0.4) (0.65,0.1)};
\end{axis}
\end{tikzpicture}

Unfortunately I just do not know if that is really part of the answer.

Best Answer

There's no inbuilt functionality for this, but you can add it yourself relatively easily by making use of the \coordindex macro that holds the index of the current coordinate:

\pgfplotsset{
    name nodes near coords/.style={
        every node near coord/.append style={
            name=#1-\coordindex,
            alias=#1-last,
        },
    },
    name nodes near coords/.default=coordnode
}

If you then add name nodes near coords to your \addplot options, the nodes will be named from <node name>-1 to <node name>-<max>, with <node name> either specified using the optional argument or defaulting to coordnode. The last node for each plot will be named <node name>-last.

Here's an example of how this could be used:

\documentclass{article}

\usepackage{pgfplots}
\usepackage{pgfplotstable}

\pgfplotsset{
    name nodes near coords/.style={
        every node near coord/.append style={
            name=#1-\coordindex,
            alias=#1-last,
        },
    },
    name nodes near coords/.default=coordnode
}

\begin{document}

\begin{tikzpicture}

\begin{axis}[
    nodes near coords,
    ]
\addplot+[only marks,   name nodes near coords=myname] coordinates {
(0.5,0.2) (0.2,0.1) (0.7,0.6)
(0.35,0.4) (0.65,0.1)};
\addplot+[only marks,   name nodes near coords=secondname] coordinates {
(0.3,0.3) (0.2,0.2) (0.4,0.6)
(0.7,0.4) (0.6,0.1)};
\end{axis}
\draw (myname-0) -- (myname-last);
\draw (secondname-3) to [out=180, in=0] (secondname-2);
\end{tikzpicture}

\end{document}
Related Question