Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'd like to have a barplot with bars side-by-side and with alternating colors. It should look like the ouput of the code below, just with alternating bar colors. (Got the idea from here)

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.10}

\begin{document}

\begin{tikzpicture}
\begin{axis}[ybar interval, xmin=0, xmax=0.3,]
\addplot+[bar shift=0pt] coordinates
    {(0,2) (0.1,1) (0.2,0.5) (0.3,0.7)};
\end{axis}
\end{tikzpicture}

\end{document}

In the manual I only see options for plots that are added as separate plots, but I don't know how to align them properly. And my search only finds solutions with separated bars that can have different colors. How can I accomplish the task to have bars with different colors besides each other in pdflatex?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

You can use two \addplot commands, checking whether the current coordinate index is odd or even using the ifthen package:

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\usepackage{ifthen}

\begin{document}

\pgfplotstableread{
0   2
0.1 1
0.2 0.5
0.3 0.7
}\datatable

\begin{tikzpicture}
\begin{axis}[ybar, bar width=0.1, bar shift=0pt, xmin=-0.1, xmax=0.4,]
\addplot +[x filter/.code={\ifthenelse{\isodd\coordindex}{\def\pgfmathresult{}}{}}] table {\datatable};
\addplot +[x filter/.code={\ifthenelse{\isodd\coordindex}{}{\def\pgfmathresult{}}}] table {\datatable};
\end{axis}
\end{tikzpicture}

\end{document}
share|improve this answer

A very small variant of Jake's answer, without the ifthen package, simply using \ifodd...\else...\fi instead:

% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass[tikz]{standalone}

\usepackage{pgfplots}
\pgfplotsset{compat=1.10}

\begin{document}

\pgfplotstableread{
    0   2
    0.1 1
    0.2 0.5
    0.3 0.7
    }\datatable

\begin{tikzpicture}
    \begin{axis}[ybar, bar width=0.1, bar shift=0pt, xmin=-0.1, xmax=0.4,]
        \addplot +[x filter/.code={\ifodd\coordindex\def\pgfmathresult{}\fi}] table {\datatable};
        \addplot +[x filter/.code={\ifodd\coordindex\relax\else\def\pgfmathresult{}\fi}] table {\datatable};
    \end{axis}
\end{tikzpicture}

\end{document}
share|improve this answer
    
Ah, yes! I thought the ifthen package provided the \ifodd command. Silly. –  Jake Jul 16 at 17:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.