[Tex/LaTex] How to add a legend in aligned subplots


I want to have two subplots with the same x axis aligned above one another.
In the manual I read, that I should use \matrix{} to achieve this.

Now I want to have legends in both plots. But since the legend box itself seems to use the matrix environment, this gives me the error "You cannot nest pgfmatrix environments, yet."

Here is a reduced example of what does not work:

        \addplot {x} ;

Any ideas?

Best Answer

This is a known limitation of TikZ matrizes - and of pgfplots legends in such a context as well.

There are a couple of possible alternatives to solve the problem:

  1. to detach the legend and place it (say) below your array of subplots

  2. to use a LaTeX table for the array alignment

  3. groupplots (but only if the involved axes share a common axis).

The details along with a lot of examples have been documented in the pgfplots manual http://pgfplots.sourceforge.net/pgfplots.pdf (perhaps your version of the manual belongs to an older version in which this section is not up to date).