[Tex/LaTex] Zero space between bars in pgfplots bar graph

bar chartpgfplots

I want to draw a bar graph with the bars touching, like in a histogram, using pgfplots. This is basically what I'm aiming for:
Bar graph with bars touching

That plot is generated with this code:

\documentclass{article}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[ybar]
        \addplot[fill=gray, bar width=41] plot coordinates
            {(1,160) (2,-50) (3,-98) (4,95) (5,270)};
    \end{axis}
\end{tikzpicture}

\end{document}

The problem with my code is that the value for the bar width key was found by trial and error, doesn't place the bars exactly right, and needs to be changed if I want to change the size of the graph.

I was expecting to be able to do something like this:

\documentclass{article}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[ybar, width=\textwidth,]
        \addplot[fill=gray, bar width=0.2\textwidth] plot coordinates
            {(1,160) (2,-50) (3,-98) (4,95) (5,270)};
    \end{axis}
\end{tikzpicture}

\end{document}

but that makes the bars too wide:
Bars too wide

Ideally I'd like a solution that scales with changes in the size of the graph.

Best Answer

Percusse's suggestion of using ybar interval is a good idea, as this will give you perfectly aligned bars without gaps between them.

Note that you will have to provide a dummy data point at the end of your data, as the ybar interval style needs to know how wide the last bar has to be. In this example, you could add a coordinate like (6,0) (the y component doesn't matter here, only the x component is used).

To get tick marks and labels that are centred with respect to the bars, you'll have to use a bit of trickery: The ybar interval bars will go from 1 to 2, and 2 to 3, so their centres won't be round values. To fix this, we can use an x filter/.code to shift the bars to the left by 0.5. By default, the ybar interval key sets xtick=data, so the start of each bar would be used for the tick positions. This is not what we want in this case, so we'll have to switch it off using xtick={}. This turns the normal tick placement mechanism back on.

\documentclass{article}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
        enlarge x limits=false,
        ybar interval,
        x tick label as interval=false,
        x filter/.code=\pgfmathparse{#1-0.5},
        xtick={},
        xmajorgrids=false
    ]
        \addplot[fill=gray] plot coordinates
            {(1,160) (2,-50) (3,-98) (4,95) (5,270) (6,0)};
    \end{axis}
\end{tikzpicture}

\end{document}