[Tex/LaTex] Graphing the Thomae Function

tikz-pgf

Could someone please give me guidance on how to plot this special function? I honestly have no idea where even to start (I've never actually done a \tikzpicture from scratch).

\[
f(x) = \left\{\begin{array}{lr}
    0, &x \ \text{irrational}\\
    \frac{1}{q}, &x = \frac{p}{q} \  \text{in lowest form}\\[10pt]
    \end{array}\right\}

]

It should look something like this:

enter image description here

Best Answer

Welcome to TeX.SE! Here is a proposal. Of course, this is just a cartoon because I had to cut off q, as is done in your screen shot.

EDIT: In my previous version there was a huge conceptual flaw. Big big thanks to Peter Grill for bringing it to my attention!

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[scale=8]
\draw [-stealth] (-0.1,0) -- (1.1,0);
\draw [-stealth] (0,-0.1) -- (0,0.6);
\foreach \X in {1,...,7}
{\ifnum\X=1
\else
\draw (0.02,1/\X) -- (-0.02,1/\X) node[left,xshift={(-(1+pow(-1,\X)))*3pt}]{$\frac{1}{\X}$};
\fi
}
\foreach \X [evaluate=\X as \Ymax using {int(\X-1)}]in {25,24,...,2}
{\foreach \Y in {1,...,\Ymax}
 {\ifnum\X<6
 \draw (\Y/\X,0.02) -- (\Y/\X,-0.02) node[below,fill=white]{$\frac{\Y}{\X}$};
 \else
 \draw[ultra thin] (\Y/\X,0.01) -- (\Y/\X,-0.01);
 \fi
 \pgfmathtruncatemacro{\TST}{gcd(\X,\Y)}
 \ifnum\TST=1
 \fill ({\Y/\X},1/\X) circle(0.2pt); 
 \fi
 }
}
\foreach \X in {0,1,...,80}
{\fill (\X/80,0) circle(0.2pt); }
\end{tikzpicture}
\end{document}

enter image description here

Related Question