Graphics, Figures & TablesTikz calculations

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

Tikz calculations

Post by mtanner »

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:

Code: Select all

\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.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

User avatar
Stefan Kottwitz
Site Admin
Posts: 10323
Joined: Mon Mar 10, 2008 9:44 pm

Tikz calculations

Post by Stefan Kottwitz »

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
LaTeX.org admin
User avatar
Stefan Kottwitz
Site Admin
Posts: 10323
Joined: Mon Mar 10, 2008 9:44 pm

Tikz calculations

Post by Stefan Kottwitz »

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.

Code: Select all

\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
ellipse.png (11.56 KiB) Viewed 4866 times
Just for fun as I stumbled across this topic again. With compilable code I would have figured it out earlier.

Stefan
LaTeX.org admin
Post Reply