8

An easy way to write axis labels in Tikz is:

\foreach \x/\xtext in {-1,-0.5,0.5,1}
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};

Is it possible to have something similar but where \x and \xtext do not get the values from the same list as follows ?

\foreach \x in {-1,-0.5,0.5,1}/\xtext in {-10,-5,5,10}
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
pluton
  • 16,421

2 Answers2

12

Here a simple code. Is this what you want?

\begin{tikzpicture}
\draw[very thin,gray] (-1,0)--(1,0);
\foreach \x/\xtext in {-1/a_0,-0.5/a_1,0.5/a_2,1/a_3}{
\draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\xtext$};
}
\end{tikzpicture}

enter image description here

Sigur
  • 37,330
  • 1
    yes, it is nice. I have to experiment. – pluton Jan 26 '13 at 20:44
  • 2
    @pluton I know this is not the core of this question, but in this case, one could also use the count key: \foreach \x[count=\xIndex from 0] and then use $a_{\xIndex}$. – Qrrbrbirlbel Jul 12 '13 at 16:29
10

If your lists are from different sources, then you would need to merge them as follows:

\documentclass{article}
\usepackage{tikz}
\makeatletter
% \specialmergetwolists{<coupler>}{<list1>}{<list2>}{<return macro>}
% \specialmergetwolists*{<coupler>}{<listcmd1>}{<listcmd2>}{<return macro>}
\protected\def\specialmergetwolists{%
  \begingroup
  \@ifstar{\def\cnta{1}\@specialmergetwolists}
    {\def\cnta{0}\@specialmergetwolists}%
}
\def\@specialmergetwolists#1#2#3#4{%
  \def\tempa##1##2{%
    \edef##2{%
      \ifnum\cnta=\@ne\else\expandafter\@firstoftwo\fi
      \unexpanded\expandafter{##1}%
    }%
  }%
  \tempa{#2}\tempb\tempa{#3}\tempa
  \def\cnta{0}\def#4{}%
  \foreach \x in \tempb{%
    \xdef\cnta{\the\numexpr\cnta+1}%
    \gdef\cntb{0}%
    \foreach \y in \tempa{%
      \xdef\cntb{\the\numexpr\cntb+1}%
      \ifnum\cntb=\cnta\relax
        \xdef#4{#4\ifx#4\empty\else,\fi\x#1\y}%
        \breakforeach
      \fi
    }%
  }%
  \endgroup
}
\makeatother

\begin{document}
\specialmergetwolists{/}{-1,-0.5,0.5,1}{a_0,a_1,a_2,a_3}\clist
% If the lists are in macros, use the star (*) form:
% \def\alist{-1,-0.5,0.5,1}
% \def\blist{a_0,a_1,a_2,a_3}
% \specialmergetwolists*{/}\alist\blist\clist

\begin{tikzpicture}
\draw[very thin,gray] (-1,0)--(1,0);
\foreach \x/\y in \clist{
  \draw[very thin,gray] (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\y$};
}
\end{tikzpicture}
\end{document}
Ahmed Musa
  • 11,742
  • Just what I needed! The semantics are like Python's zip: the merged list is truncated to match the shorter of the two input lists: \specialmergetwolists{/}{-1,-0.5,0.5}{a_0,a_1,a_2,a_3}\clist puts -1/a_0,-0.5/a_1,0.5/a_2 in \clist. – joeln Jul 11 '13 at 01:26
  • 1
    This should become part of tikz-pgf. – Janosh Aug 30 '20 at 15:25
  • what if one list is a macro and one is a sequence of integers? – Hugh Perkins Apr 04 '21 at 15:08