5

Consider the following code:

\documentclass[border=2pt]{standalone}

\usepackage{pgfplots}

\newcommand\myxtick[1]{\foreach \x in {2,3,4}{\x,}#1}
\newcommand\otherxtick{2,3,4,5}

\begin{document}  
\begin{tikzpicture}
    \begin{axis}[
        %xtick={\myxtick[5]},
        xtick={\otherxtick},
        xmax=10,xmin=0,ymax=10,domain=0:10]
    \addplot {x};
    \end{axis}
\end{tikzpicture}
\end{document}

If I specify the xtick with \otherxtick the code works but if I use \myxtick[5] it gives me errors and it does not compile. I tried also with xtick./expanded={\myxtick[5]}, xtick./expand once={\myxtick[5]} and xtick./expand twice={\myxtick[5]} but with the same result.

I took a look also at these question but with no result:

I ask this question because the notation {1,2,...,20} for the definition of ticks can not always be used. Consider for example a dateplot in which you want ticks every 3 years from 1900 to 1960. If I write {1900-01-01,1903-01-01,...,1960-01-01} it does not works and write all 21 ticks is very boring...

Red
  • 10,181

1 Answers1

6

The problem lies in the way in which you defined the list. \othertick is a "good" list, while \myxtick is not.

What you need is a kind of command able to create the list to be passed to xtick: to do so, you have to take into account where does the list separator (the comma) goes as well as the fact that the foreach groups things, thus the list created that way is not global.

One solution is:

\newcommand{\deflisttick}[1]{
\gdef\listticks{}% global list
\foreach \x[count=\xi] in {#1}{\global\let\maxitems\xi}% count the max number of items
\foreach \x[count=\xi] in {#1}{
 \ifnum\xi=\maxitems
   \xdef\listticks{\listticks \x}
 \else
   \xdef\listticks{\listticks \x,}
 \fi
}
}

In this case I check the last element of the list: when it's processed no final comma is added on the list (there are also other ways to accomplish this).

Then in the document you call:

\deflisttick{1,3,...,9}

and this will create: 1,3,5,7,9. An example:

\documentclass[border=2pt]{standalone}

\usepackage{pgfplots}

\newcommand{\deflisttick}[1]{
\gdef\listticks{}% global list
\foreach \x[count=\xi] in {#1}{\global\let\maxitems\xi}% count the max number of items
\foreach \x[count=\xi] in {#1}{
 \ifnum\xi=\maxitems
   \xdef\listticks{\listticks \x}
 \else
   \xdef\listticks{\listticks \x,}
 \fi  
}
}

\begin{document}
\deflisttick{1,3,...,9}
\begin{tikzpicture}
    \begin{axis}[
        xtick={\listticks},
        xmax=10,xmin=0,ymax=10,domain=0:10]
    \addplot {x};
    \node at (axis cs: 2,5){\listticks};% debug purposes
    \end{axis}
\end{tikzpicture}
\end{document}