A classic way of displaying categories with corresponding values is a bar chart. It consists of rectangular bars, and they are proportional to the represented values. The main purpose is to visually compare those values.
We can use vertical or horizontal bars.
How to do it…
We will use the pgfplots
package. It’s for natively plotting in LaTeX with a convenient user interface. We will use it to produce a horizontal bar chart. Perform these steps:
- Start with a document class:
\documentclass{article}
- Load the
pgfplots
package:\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.8} - Begin the document:
\begin{document}
- Begin a TikZ picture, which will be the container for the plot:
\begin{tikzpicture}
- Open an
axis
environment:\begin{axis}
- Give options to the axis:
[
title = Contributions per category
at LaTeX-Community.org,
xbar,
y axis line style = { opacity = 0 },
axis x line = none,
tickwidth = 0pt,
enlarge y limits = 0.2,
enlarge x limits = 0.02,
nodes near coords,
symbolic y coords = {LaTeX, Tools,
Distributions, Editors},
] - Add a plot:
\addplot coordinates { (57727,LaTeX) (5672,Tools)
(2193,Distributions) (11106,Editors) }; - Add another plot:
\addplot coordinates { (14320,LaTeX) (1615,Tools)
(560,Distributions) (3075,Editors) }; - Then add a legend:
\legend{Topics, Posts}
- End the
axis
environment, the TikZ picture, and the whole document:\end{axis}
\end{tikzpicture}
\end{document} - Compile, and take a look:
How it works…
The \addplot
command does the plotting work; we called it with a set of specific coordinates. In our case, we used numeric values together with symbolic coordinates for the subjects.
We design the plot by options to the axis
environment. This is the specific pgfplots
environment with a lot of options for customizing. Here’s what we did:
- We provided a title.
- We set
xbar
as a style to get bars in the x direction. Specifically, this means that horizontal bars will be placed from y=0 to the x coordinate. - Omitting unnecessary diagram parts means less distraction. This helps in focusing and understanding the contents. Therefore, we:
- Chose a completely opaque line style for the y axis so that it won’t be printed
- Hid the x axis using axis x line = none
- Removed the x axis ticks by setting their width to 0
- Then we enlarged the x and y limits a bit to get a better display.
- We placed the nodes with values near the bars by enabling the
nodes near coords
option. - We defined symbolic coordinates as y values so that we could assign numeric (x) values to (y) subjects.
To sum up, xbar
defined the plot style, and symbolic y coords
let us use string values. The other axis options were just for the design. There are many more possible settings, so for further customization, refer to the pgfplots
manual. You can open it by entering texdoc pgfplots
in command prompt or visiting http://texdoc.net/pkg/pgfplots.
Navigate: