[Tex/LaTex] Axis limits in user-defined style

pgfplots

(related but unequal question: Using Macro Defined Lists in TikZ/PGFplots)

I'm having several axis-environments inside the same tikzpicture. I would like to have some (but not all) share the same xmin and xmax, and some (but not all) share the same ymin and ymax. I tried to do that by defining it in my own style, in the same way that I set xlabel, ylabel, and other axis-specific styles.

Below is a minimal, not-working example. When I run it with pgfplots 2011/07/29 v1.5 (git show 1.5-1-gcc2f2d2 ), it fails with the error message:

! Package pgfplots Error: Sorry, you can't change `/pgfplots/xmax' in this context. Maybe you need to provide it as \begin{axis}[/pgfplots/xmax=...] ?.

I have two closely related questions:

  1. Why can I set xlabel, ylabel, ytick, but not ymin? Is there a fundamental reason for this, or is it just a lack of implementation?
  2. How can I achieve the effect of applying a particular set of xmin, xmax, ymin, ymax, to more than one axis?

This related question ( Using Macro Defined Lists in TikZ/PGFplots) might provide a working solution (q. 2), but does not answer my understanding-related question (q. 1).

Minimal (not) Working Example

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}
\begin{document}
\begin{tikzpicture}[
    spam/.style={%
        /pgfplots/ylabel={Spam (kg)},%
        /pgfplots/xlabel={Eggs (no.)},
        /pgfplots/ytick={0,10,...,200}, % this works
%        /pgfplots/xmax=3, this fails!
        }]
\begin{axis}[spam]
\addplot coordinates {(0, 0) (1, 1) (2, 2)};
\end{axis}

\begin{axis}[spam, at={(5cm, 3cm)}]
\addplot coordinates {(-1, 0) (-1, 1) (1, 0)};
\end{axis}
\end{tikzpicture}
\end{document}

Best Answer

Rather than defining your style in the first plot, you can define it in your pre-amble using \pgfplotsset; this allows you to put xmin, xmax, etc in your own style.

screenshot

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}

\pgfplotsset{mystyle/.style={%
        width=6cm,
        ylabel={mystyle (kg)},
        xlabel={Eggs (no.)},
        xmin=-2,xmax=3,
        xtick={-2,-1,...,3}}}

\begin{document}

\begin{tikzpicture}
\begin{axis}[mystyle]
\addplot coordinates {(0, 0) (1, 1) (2, 2)};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[mystyle]
\addplot coordinates {(-1, 0) (-1, 1) (1, 0)};
\end{axis}
\end{tikzpicture}

\end{document}

And if you want to inherit some of the properties from mystyle and overwrite others, then you can use, for example,

\begin{axis}[mystyle,xmin=-10,xmax=5,xtick={-5,-2,5}]