## LaTeX forum ⇒ Graphics, Figures & Tables ⇒ Tikz calculations

Information and discussion about graphics, figures & tables in LaTeX documents.
mtanner
Posts: 1
Joined: Sat Jul 22, 2017 9:55 am

### Tikz calculations

I am writing some Tikz code to draw multiple ellipses within a rectangle. I want to change the fill color of the ellipses based on a counter. So the code I have is:

\def\clr{ref};   % initial color\def\count{0}; % counter \foreach \col in {1,...,\numcols}  {    \foreach \row in {1,...,\numrows}       {         \pgfmathsetmacro{\count}{\count+1};         % calculate position and dimension of an ellipse         \ifthenelse{\count>6} {\def\clr{blue}} {};         \draw[fill=\clr] .....  % draw the ellipse       }  }

The ellipses are always filled with red. I have tried variations of the code to change \clr, but never with any effect. What is wrong with my code?

I cannot confirm that the value of \count is actually being updated by \pgfmathsetmacro.

Stefan Kottwitz
Posts: 8980
Joined: Mon Mar 10, 2008 9:44 pm
Welcome to the forum!

Can you perhaps post the complete TikZ picture code, so we can test and fix it? Maybe it's caused because the calculation of \pgfmathsetmacro gives 1.0 for example, instead of 1. With code I could test and fix it (the code above is not compilable).

Stefan

Stefan Kottwitz
Posts: 8980
Joined: Mon Mar 10, 2008 9:44 pm
I guess \ifthenelse was not properly used. Hard to say without code that can be tested.

Anyway, now I got some time to complete your code to have a compilable example, and I fixed it. I made it easier using a classic LaTeX counter instead of pgfmath.

\documentclass[margin=10pt]{standalone}\usepackage{tikz}\usetikzlibrary{math}\usepackage{ifthen}\newcounter{count}\begin{document}\begin{tikzpicture}   \def\clr{red}% initial color  \setcounter{count}{0}% initial counter   \foreach \col in {1,...,6}  {    \foreach \row in {1,...,3}       {         \stepcounter{count}         \ifthenelse{\value{count}>6}{\def\clr{blue}}{}         \draw[fill=\clr] (\col,\row) ellipse (1cm and 1cm);       }  }\end{tikzpicture}\end{document}

ellipse.png (11.56 KiB) Viewed 841 times

Just for fun as I stumbled across this topic again. With compilable code I would have figured it out earlier.

Stefan