7

I want to draw a rectangle around an axis created using pgfplots. This is a minimal example:

\documentclass{minimal}

\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[axis background/.style={fill=blue!10, draw=black, line width=1pt},
    axis x line=center, axis y line=center, 
    xmin=-1, xmax=1, ymin=-1, ymax=1]
\addplot {x};
\end{axis}
\end{tikzpicture}
\end{document}

Here is what it creates:

Picture of output

As you can see, the left draw/stroke on the axis background is missing. Anybody know what the problem is?

7

The command that draws the two-dimensional axis appears to be lacking a \pgfpathclose command (I'll file a bug report for this). In the meantime, you can work around the problem by using insert path={ \pgfextra{\pgfplots@clippath@install{} \pgfpathclose} } in your axis background style.

In the example below, I've wrapped the insert path in a new style called closed background.

\documentclass{minimal}

\usepackage{tikz}
\usepackage{pgfplots}

\makeatletter
\tikzset{
    closed background/.style={
        insert path={
            \pgfextra{\pgfplots@clippath@install{} \pgfpathclose}
        }
    }
}
\makeatother

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis background/.style={
        fill=blue!10,
        draw=black,
        line width=1pt,
        line cap=round,
        closed background
    },
    axis lines*=center, 
    xmin=-1, xmax=1, ymin=-1, ymax=1]
\addplot {x};
\end{axis}
\end{tikzpicture}
\end{document}
2
  • Thanks. Looking forward to seeing the fix implemented in the next release.
    – TSGM
    Dec 7 '11 at 22:50
  • Thanks for the bug report. I have fixed fixed the bug in pgfplots. Dec 10 '11 at 8:22
6

I am not sure why axis background does not draw the left line. However, you can use the backgrounds library to add a background rectangle which by default appears to produce better results by adding a separation between the axis and the box. Note that the grey box is the result of cropping, and not part of the graph:

enter image description here

\documentclass[border=5pt]{standalone}

\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{backgrounds}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis x line=center, axis y line=center,
    xmin=-1, xmax=1, ymin=-1, ymax=1,
    /tikz/background rectangle/.style={
        fill=blue!10,
        draw=black,
        line width=1pt
    },
    show background rectangle
    ]
\addplot {x};
\end{axis}
\end{tikzpicture}
\end{document}
1
  • Brilliant. I used this workaround (the tikz background is preferable), although Jake's answer was officially accepted since it located the actual problem.
    – TSGM
    Dec 7 '11 at 22:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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