4

I have a scatter plot in which I want to label each data point.

Here is my MWE:

\documentclass{standalone}
\usepackage{pgfplots,pgfplotstable,tikz}
\def\axisdefaultwidth{12cm}
\def\axisdefaultheight{8cm}
\pgfplotsset{every axis/.style={scale only axis}}

\begin{filecontents*}{data.txt}
1   3.3941  -0.010854
2   3.635   -0.0090022
3   5.3026  -0.018046
4   6.1734  -0.023502
5   6.3859  -0.020395
6   7.1966  -0.030667
7   7.2646  -0.021628
8   8.451   -0.042211
9   9.1093  -0.035184
10  10.002  -0.043009

\end{filecontents*}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
            \node[shape=circle,draw,inner sep=1.2pt] (char) {#1};}}

\begin{document}
\begin{tikzpicture}
\begin{axis}[xtick pos=left,
ytick pos=left,
  xlabel= $x$,
  ylabel= $y$       ]
\addplot [only marks, color=black, mark=*,mark size =1.8] table [x index=1, y index =2] {data.txt};
\draw[<-] (axis cs:3.3941, -0.010854) -- (axis cs:3.3941, -0.0150);
\node at (axis cs:3.3941, -0.016){\circled{1}};
\end{axis}
\end{tikzpicture}
\end{document}

The result looks like this: enter image description here

Look at the circled label. That's how I want the numbering to be. However, I want to automate this numbering/labeling process and the label for each point should be taken from corresponding row of the first column of the file.

Is there any easy way of doing this?

7

You can make use of nodes near coords:

output of code

\documentclass[border=5mm]{standalone}
\usepackage{pgfplotstable,filecontents}
\def\axisdefaultwidth{12cm}
\def\axisdefaultheight{8cm}
\pgfplotsset{every axis/.style={scale only axis}}

\begin{filecontents*}{data.txt}
1   3.3941  -0.010854
2   3.635   -0.0090022
3   5.3026  -0.018046
4   6.1734  -0.023502
5   6.3859  -0.020395
6   7.1966  -0.030667
7   7.2646  -0.021628
8   8.451   -0.042211
9   9.1093  -0.035184
10  10.002  -0.043009

\end{filecontents*}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
  xtick pos=left,
  ytick pos=left,
  xlabel= $x$,
  ylabel= $y$,
  ymin=-0.05, % to give room for the last pin
  every node near coord/.style={
   inner sep=0pt,
   anchor=center,
   pin={[circle,draw,inner sep=1pt]below:\pgfplotspointmeta}}
  ]
\addplot [
   only marks,
   color=black,
   mark=*,
   mark size=1.8,
   nodes near coords={}, % set node content of nodes near coords to be empty
   point meta=explicit symbolic
] table [meta index=0,x index=1, y index =2] {data.txt};
\end{axis}
\end{tikzpicture}
\end{document}
  • This is neat! How can I adjust the length of the line connecting the label circle and the data point? – Rhinocerotidae Dec 3 '17 at 14:45
  • @SaravanaKumar \begin{tikzpicture}[pin distance=10pt] – Torbjørn T. Dec 3 '17 at 14:45
  • 1
    @SaravanaKumar Meant pin distance, sorry. – Torbjørn T. Dec 3 '17 at 14:46

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.