9

I often find myself wanting to use some feature that allows me to loop through several sets where the nth item in each list is paired together with the nth item in the other lists.

\begin{tikzpicture}
\draw [->] (0,0) -- (7,0) node[right] {$x$};
\draw [->] (0,0) -- (0,6) node[above] {$y$};
% Let's say I have several values to label on the graph
\foreach \x in {1,5,6,2,1,6,3,1}
\foreach \y in {0,3,4,0.5,2,3,1.5,4}
\foreach \point in {A,B,C,D,E,F,G,H}
\draw [fill = black] (\x,\y) circle (1 mm) node[left] {\point};
% This draws every combination from the three lists which is a huge mess!

% What I want it to draw is
\draw [fill = black] (4,2)      circle (1 mm) node[left] {A};
\draw [fill = black] (5,3)      circle (1 mm) node[left] {B};
\draw [fill = black] (6,4)      circle (1 mm) node[left] {C};
\draw [fill = black] (2,0.5)    circle (1 mm) node[left] {D};
\draw [fill = black] (1,2)      circle (1 mm) node[left] {E};
\draw [fill = black] (6,3)      circle (1 mm) node[left] {F};
\draw [fill = black] (3,1.5)    circle (1 mm) node[left] {G};
\draw [fill = black] (1,4)      circle (1 mm) node[left] {H};
\end{tikzpicture}

Is there a clean, easy way to do this?

1
  • 4
    like this \foreach \x/\y/\z in {1/2/3,4/5/6}{...}?
    – percusse
    Apr 14 '18 at 0:31
14

Like this?

\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \foreach\x/\y/\z in {4/2/A,5/3/B,6/4/C,2/.5/D,1/2/E,6/3/F,3/1.5/G,1/4/H}
  \draw [fill = black] (\x,\y)circle (1 mm) node[left] {\z};
\end{tikzpicture}
\end{document}

enter image description here

2
  • Like this? Are you unsure?
    – Werner
    Apr 14 '18 at 0:35
  • 1
    You can probably use two variables like this \foreach\p/\z in {(4,2)/A,(5,3)/B,(6,4)/C,(2,.5)/D,(1,2)/E,(6,3)/F,(3,1.5)/G,(1,4)/H} with \p in place of (\x,\y) ? Or only one like this \foreach[count=\z from 65]\p in {(4,2),(5,3),(6,4),(2,.5),(1,2),(6,3),(3,1.5),(1,4)} with \char\z in place of \z ?
    – Kpym
    Apr 14 '18 at 9:50
7

Also with pgfplots

\documentclass[border=2pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines=left,xmin=0,ymin=0, xmax=7.5, ymax=7.5]
\addplot+[only marks, nodes near coords=\csname @Alph\endcsname{\numexpr\coordindex+1}] 
     coordinates {(4,2)(5,3)(6,4)(2,0.5)(1,2)(6,3)(3,1.5)(1,4)};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

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.