pgfplots: put a tick each first day of a month
The problem with your approach is that no expansion takes place when the option xtick={\dateticks}
is processed. xtick
represents a list with just one element, namely \dateticks
.
One way around this is to put the picture into a macro and provide the list as an argument.
\newcommand\mygraph[1]{... xtick={#1} ...}
Now it is easy to expand \dateticks
before handing it over to \mygraph
.
\expandafter\mygraph\expandafter{\dateticks}
Before doing so we have to make sure that \dateticks
contains the list of dates, and nothing else.
\newcommand\dateticks{2016-01-01}
\foreach \i in {2,...,12}{\xdef\dateticks{\dateticks,2016-\ifnum\i<10 0\fi\i-01}}
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepgfplotslibrary{dateplot}
\newcommand\dateticks{2016-01-01}
\foreach \i in {2,...,12}{\xdef\dateticks{\dateticks,2016-\ifnum\i<10 0\fi\i-01}}
\newcommand\mygraph[1]%
{\begin{tikzpicture}
\begin{axis}%
[date coordinates in=x,
xtick={#1},
xticklabel=\day/\month,
xticklabel style={rotate=90},
]
\addplot coordinates {(2016-01-23,10) (2016-03-05,20) (2016-09-14,10)};
\end{axis}
\end{tikzpicture}%
}
\begin{document}
\expandafter\mygraph\expandafter{\dateticks}
\end{document}
Edit: Here is a way to generate the ticks for an arbitrary start date and an arbitrary number of months. After executing
\setdateticks{YYYY-MM-DD}{N}
the macro \dateticks
contains a list of N dates starting with YYYY-MM-DD and incrementing the month by one from date to date. E.g., \setdateticks{2016-12-01}{3}
sets \dateticks
to 2016-12-01,2017-01-01,2017-02-01
. Here is the code defining \setdateticks
.
\newcommand\dateticks{}
\newcommand\splitdate{}
\def\splitdate#1-#2#3-#4-%
{\def\YYYY{#1}%
\ifnum#2=0\def\MM{#3}\else\def\MM{#2#3}\fi
\def\DD{#4}%
}
\newcommand\setdateticks[2]%
{\def\dateticks{#1}%
\bgroup
\splitdate#1-%
\foreach \i in {2,...,#2}
{\pgfmathtruncatemacro\mm{mod(\MM+\i-2,12)+1}%
\pgfmathtruncatemacro\yyyy{\YYYY+divide(\MM+\i-2,12)}%
\xdef\dateticks{\dateticks,\yyyy-\ifnum\mm<10 0\fi\mm-\DD}%
}%
\egroup
}
And here is the complete code for the diagram above.
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepgfplotslibrary{dateplot}
\newcommand\dateticks{}
\def\splitdate#1-#2#3-#4-%
{\def\YYYY{#1}%
\ifnum#2=0\def\MM{#3}\else\def\MM{#2#3}\fi
\def\DD{#4}%
}
\newcommand\setdateticks[2]%
{\def\dateticks{#1}%
\bgroup
\splitdate#1-%
\foreach \i in {2,...,#2}
{\pgfmathtruncatemacro\mm{mod(\MM+\i-2,12)+1}%
\pgfmathtruncatemacro\yyyy{\YYYY+divide(\MM+\i-2,12)}%
\xdef\dateticks{\dateticks,\yyyy-\ifnum\mm<10 0\fi\mm-\DD}%
}%
\egroup
}
\newcommand\mygraph[1]%
{\begin{tikzpicture}
\begin{axis}%
[date coordinates in=x,
xtick={#1},
xticklabel=\day/\month,
xticklabel style={rotate=90},
]
\addplot coordinates {(2016-01-23,10) (2016-03-05,20) (2016-09-14,10)};
\end{axis}
\end{tikzpicture}%
}
\begin{document}
\setdateticks{2016-01-01}{12}
\expandafter\mygraph\expandafter{\dateticks}
\end{document}