LaTeX forum ⇒ Graphics, Figures & TablesTikz calculations

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

Tikz calculations

Postby mtanner » Fri Sep 29, 2017 1:17 pm

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:


  1. \def\clr{ref}; % initial color
  2. \def\count{0}; % counter
  3.  
  4. \foreach \col in {1,...,\numcols}
  5. {
  6. \foreach \row in {1,...,\numrows}
  7. {
  8. \pgfmathsetmacro{\count}{\count+1};
  9. % calculate position and dimension of an ellipse
  10. \ifthenelse{\count>6} {\def\clr{blue}} {};
  11. \draw[fill=\clr] ..... % draw the ellipse
  12. }
  13. }


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.

User avatar
Stefan Kottwitz
Site Admin
Posts: 8733
Joined: Mon Mar 10, 2008 9:44 pm
Location: Hamburg, Germany
Contact:

Postby Stefan Kottwitz » Sat Sep 30, 2017 8:50 am

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
Site admin

User avatar
Stefan Kottwitz
Site Admin
Posts: 8733
Joined: Mon Mar 10, 2008 9:44 pm
Location: Hamburg, Germany
Contact:

Postby Stefan Kottwitz » Wed Dec 20, 2017 11:10 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.

  1. \documentclass[margin=10pt]{standalone}
  2. \usepackage{tikz}
  3. \usetikzlibrary{math}
  4. \usepackage{ifthen}
  5. \newcounter{count}
  6. \begin{document}
  7. \begin{tikzpicture}
  8. \def\clr{red}% initial color
  9. \setcounter{count}{0}% initial counter
  10. \foreach \col in {1,...,6}
  11. {
  12. \foreach \row in {1,...,3}
  13. {
  14. \stepcounter{count}
  15. \ifthenelse{\value{count}>6}{\def\clr{blue}}{}
  16. \draw[fill=\clr] (\col,\row) ellipse (1cm and 1cm);
  17. }
  18. }
  19. \end{tikzpicture}
  20. \end{document}


ellipse.png
ellipse.png (11.56 KiB) Viewed 611 times


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

Stefan
Site admin


Return to “Graphics, Figures & Tables”

Who is online

Users browsing this forum: No registered users and 5 guests