About
Shop
LaTeX
Software
Books
Gallery
News
Contact
Blog
Settings
Latest news 2019-12-05: new blog post "RSS Feeds and Other Notifications."

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:
\DTLloaddbtex{\totals}{totals.dbtex}

% set segment colours:

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

\begin{document}
% Add the legend to the pie chart hook:
\renewcommand{\DTLpieatbegintikz}{%
\node[at=(45:\DTLradius),anchor=south west]
{%
  \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}

Download datapie-books.tex or datapie-books.pdf.

© 2015 Dickimaw Books. "Dickimaw", "Dickimaw Books" and the Dickimaw parrot logo are trademarks. The Dickimaw parrot was painted by Magdalene Pritchett.

Terms of Use Privacy Policy Cookies Site Map FAQs