3

Motivation

While attempting to answer Pie chart with values as angles not percent, I stucked on passing a string to a foreach.

The context

To makes things clear, I briefly introduce the context. That question asks for degrees rather than percentages in the chart, so my idea was to convert angles into percentages and call then the usual \pie command from pgf-pie.

The issue

The code:

\documentclass[tikz,border=10pt]{standalone}

%\usepackage{pgf-pie}

\newcommand{\anglepie}[1]{% \gdef\elements{} \foreach \ang/\lab[count=\xi] in {#1}{ \pgfmathtruncatemacro\perc{(\ang*100)/360} \ifnum\xi=1 \xdef\elements{\perc/\lab} \else \xdef\elements{\elements, \perc/\lab} \fi } %\pie{\elements} % ideally call this \node{\elements}; % \foreach \x/\y in {\elements} % \node[draw] at (\x/10,-1) {\y}; }

\begin{document} \begin{tikzpicture} \anglepie{10/A, 20/V, 30/C, 40/D} \end{tikzpicture} \end{document}

in principle works because the macro \elements contains a string in the right form to be passed to the foreach (following the same reasoning of Hobby path realization in convex hull approach). This has been verified thanks to \node{\elements};:

enter image description here

However, uncommenting:

\foreach \x/\y in {\elements}
\node[draw] at (\x/10,-1) {\y};

rise as errors:

! Package PGF Math Error: Unknown function `A' (in '2/A').
! Package PGF Math Error: Unknown function `V' (in '5/V').
! Package PGF Math Error: Unknown function `C' (in '8/C').

My feeling is that the string \elements is not interpreted correctly by the foreach, but I have no clues on the motivation behind. What's going on there?

1 Answers1

4

enter image description here

You need \expandafter

  \expandafter\pie\expandafter{\elements} % ideally call this
David Carlisle
  • 757,742