5

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?

2 Answers 2

5

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}
4

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}
1
  • Ah, yes! I thought the ifthen package provided the \ifodd command. Silly.
    – Jake
    Commented Jul 16, 2014 at 17:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .