[Tex/LaTex] Put numbers in legend using pgf pie

pgf-piepgfplotstikz-pgf

I would like to have the numbers that are inside the pie chart to be in the legend. How can I make that happen?

Here is the MWE:

\documentclass{article}
\usepackage{pgf-pie}
\usepackage{tikz}
\usetikzlibrary{shadows}

\begin{document}
\begin{tikzpicture}
\pie[text=legend,style=drop shadow,radius=2]{51.3/Protestant, 23.9/Roman Catholic, 3.3/Other Christian, 1.7/Jewish, 0.7/Buddhist, 0.6/Muslim, 0.4/Hindu, 1.2/Other religions, 16.1/No religion }
\end{tikzpicture}
\end{document}

EDIT:

I also have another pie chart, where the text is quite long. How can I set the width of the text so that it wraps around before the page ends? Here is what it looks like:

enter image description here

I forgot that PGF-PIE was not on CTAN. Here is a link to the google source: http://code.google.com/p/pgf-pie/

Best Answer

The pgf-pie package is not as flexible as one wishes. Unfortunately, etoolbox refuses to patch, so we do it manually.

Open up (make a copy/backup) the pgf-pie.sty file and scroll to the end, there is a part enclosed in \iflegend … \fi. Replace the enclosed scope environment with:

  \begin{scope}[node distance=+0pt]
    \foreach \p/\t  [count=\i from 0] in {#2}
    {
      \pgfpie@findColor{\i}
      \node[below=of legendpos.south west, anchor=north west, every legend entry/.try, name=legendpos] {\t\ifpienumberinlegend\legendbeforenumber\p\legendafternumber\fi};
      \node[draw, fill=\thecolor, \style, at=(legendpos.base west), anchor=south east] {};
    }
  \end{scope}

Now you can use the number in legend style (which should come after before number and after number!).

For long legend entries, you can use the every legend entry style, say

every legend entry/.append style={text width=2cm}

The setup now allows this (the node distance is set to zero as the inner ysep creates, in my opinion, enough room between the entries.

You need the positioning library for the newer below=of syntax.

Code

\documentclass[tikz]{standalone}
\usepackage{pgf-pie}
\usetikzlibrary{positioning,shadows}

\newif\ifpienumberinlegend
\pgfkeys{/number in legend/.code=
    \expandafter\let\expandafter\ifpienumberinlegend
    \csname if#1\endcsname
    \ifpienumberinlegend
    \let\legendbeforenumber\beforenumber
    \let\legendafternumber\afternumber
    \def\beforenumber##1\afternumber{}%
    \fi,
    /number in legend/.default=true
}
\begin{document}
\begin{tikzpicture}[every legend entry/.append style={text width=2cm}]
\pie[text=legend, style=drop shadow, radius=2, before number=\ (, after number=\,\%), number in legend]{51.3/Protestant, 23.9/Roman Catholic, 3.3/Other Christian, 1.7/Jewish, 0.7/Buddhist, 0.6/Muslim, 0.4/Hindu, 1.2/Other religions, 16.1/No religion }
\end{tikzpicture}
\end{document}

Output

enter image description here

Related Question