Latest news 2024-08-12: Crime fiction short story The Briefcase is now available.

# Exercise 31: A Pie Chart using datapie.sty and SQL (Solution)

This is a solution to the more adventurous part of Exercise 31.

You need the sample SQL data supplied in samples.sql. This requires a call to datatooltk before the document can be built:

datatooltk --out totals.dbtex --sqldb samples --sqluser sampleuser --sql "SELECT books.title AS booktitle, books.format AS bookformat, SUM(orders.quantity) AS total FROM orders, books WHERE orders.bookid=books.id GROUP BY orders.bookid ORDER BY total DESC"


The node containing the legend has its anchor set to south west. This makes the bottom left corner of the legend the reference point as given by the co-ordinate (specified using at).

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage[x11names]{xcolor}
\usepackage{datapie}

% load data file created by datatooltk:

% set segment colours:

\DTLsetpiesegmentcolor{1}{Aquamarine1}
\DTLsetpiesegmentcolor{2}{Goldenrod1}
\DTLsetpiesegmentcolor{3}{DeepPink1}
\DTLsetpiesegmentcolor{5}{Plum3}

\begin{document}
% Add the legend to the pie chart hook:
\renewcommand{\DTLpieatbegintikz}{%
{%
\begin{tabular}{ll}
\DTLforeach*{\totals}{\TheTitle=booktitle,\TheFormat=bookformat,\TheTotal=total}%
{%
\DTLiffirstrow{}{\\}%
\DTLdocurrentpiesegmentcolor\rule{10pt}{10pt} &
\TheTitle\ (\TheFormat)
}%
\end{tabular}%
};
}

% pie chart:
\DTLpiechart{variable=\TheTotal,
innerratio=0.8,
outerlabel={% calculate and display percentage
(\DTLpiepercent\%)}%
}% settings
{\totals}% data base
{\TheTotal=total}% assignment list

\end{document}