Saturday, April 7, 2012

Calculating values for bar charts in latex

The bchart package

If you want to add some bar charts to your latex document you might want to use bchart. This pdf by Tobias Kuhn shows some examples of how to use the package. Description taken from that pdf:
bchart is a LATEX package for drawing simple bar charts with horizontal bars
on a numerical x-axis. It is based on the TikZ drawing package. The focus of
this package is on simplicity and aesthetics.
Using the package one can display labels, specify the axis range, bar colors or unit of the values.

Calculating values

Unfortunately the package has a drawback. If you use math expressions they will be calculated for the bars but wont their values won't be displayed. In addition you cannot use \pgfmathparse{} to calculate the value for the chart because it will cause errors in displaying the bars.
\begin{bchart}[min=-100, max=100, step=25, unit=\%, width=\linewidth]

\bcbar[text=should be 100,color=green!40]{123 - 23}
\bclabel{bars group  1}

\pgfmathparse{123 - 23}
\bcbar[text=should be 100 again,color=red]{\pgfmathresult}

\pgfmathparse{123 - 23}
\bcbar[text=should be 100,color=yellow]{\pgfmathresult}
\bclabel{bars group 2}
\pgfmathparse{123 - 23}
\bcbar[text=should be 100,color=red!40]{\pgfmathresult}

\bcxlabel{this does not work properly}
Which yields:
I believe it is due to internal usage of pgfmath of the package. There is a simple solution though, using \\pgfmathsetmacro{}{}:
\begin{bchart}[min=-100, max=100, step=25, unit=\%, width=\linewidth]
\pgfmathsetmacro{\makroName}{123 - 23}
\bcbar[text=should be 100,color=green!40]{\makroName}
\bclabel{bars group  1}
\bcbar[text=should be 100 again,color=red]{\makroName}

\pgfmathsetmacro{\anotherMakro}{23*100 / 123}
\bcbar[text=calculating 23*100 / 123,color=yellow]{\anotherMakro}
\bclabel{bars group 2}
\bcbar[text=as above,color=red!40]{\anotherMakro}

\bcxlabel{this does}
Which yields:

One other way to add bar charts is to use pgfplots package. Here is an example of a bar chart with semi log y axis, labels above the bars and ticks on x axis only for bars:
 ylabel=\textsc{Average computation time[msec]},
 scale only axis,
  bar width=0.102874in, 
  bar shift=0in,
    plot coordinates {
        (1, 810)
        (2, 53405.5)
        (3, 64655)
        (4, 721.25)
        (5, 738.5)
    \node [above] at (axis cs:  1,  810) {$Q1$};
    \node [above] at (axis cs:  2,  53405.5) {$Q2$};
    \node [above] at (axis cs:  3,  64655) {$Q3$};
    \node [above] at (axis cs:  4,  721.25) {$Q4$};
    \node [above] at (axis cs:  5,  738.5) {$Q5$};
Which yields:

Visit for some tkiz examples or this for percentage barcharts.

Let me know if you've found this helpful. :)

No comments:

Post a Comment