I am trying to add a legend for two plots on two different y-axes, however they are overlapping each other and each one is being written in its own box. I would like for both of them to share a single box and not overlap each other.
Most of the examples I have seen for creating the legend assume that all series happen within a single axis
environment, but creating a second y-axis requires me to also create a second axis
environment, and I am guessing that's where I run into trouble.
Here's a MWE. What am I overlooking?
\documentclass{article}
% UNITS
\usepackage{siunitx}
\sisetup{per=slash, load=abbr}
% GRAPHICS
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.3}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
scale only axis,
scaled x ticks=base 10:3,
axis y line*=left,
xmin=0, xmax=0.06,
ymin=0, ymax=80,
xlabel=$Q/\si{\metre\cubed\per\second}$,
ylabel=$H/\si{\metre}$]
\addplot[smooth,mark=x,blue]
coordinates{
(0,68.6)
(0.0148,72)
(0.0295,68.6)
(0.0441,53.4)
(0.059,22.8)
};
% \addlegendentry{$H$}
\legend{$H$}
\end{axis}
\begin{axis}[
scale only axis,
scaled x ticks=base 10:3
/pgf/number format/sci subscript,
axis y line*=right,
axis x line=none,
xmin=0, xmax=0.06,
ymin=0, ymax=100,
ylabel=$\eta/\si{\percent}$]
\addplot[smooth,mark=*,red]
coordinates{
(0,0)
(0.0148,48)
(0.0295,66)
(0.0441,66)
(0.059,45.0)
};
% \addlegendentry{$\eta$}
\legend{$\eta$}
\end{axis}
\end{tikzpicture}
\end{document}
Best Answer
You could alter the legend of the second plot "by hand" by using
\addlegendimage{<plot options>} \addlegendentry{<plot title>}
after the second plot. You can access the<plot options>
of the first plot by assigning a\label{<name>}
to it and using the key/pgfplots/refstyle=<name>
in your\addlegendimage
command:Another option would be to label the plots directly. Since pgfplots version 1.5.1, you can place nodes a specified length along the plot by including a
node [pos=<fraction>] {}
in the\addplot
command.Depending on how you're going to use the graph, you could also consider colouring the axis to match the plots. This will be problematic if you need to print the document in black and white, but in a presentation, this might be more elegant than forcing the audience's eyes from the plot line to the legend and then to the y axes in order to match plot and axis.
I've defined a style
y axis style=<colour>
that simultaneously sets the colour fory axis line style
,y tick style
,yticklabel style
andylabel style
, so you can just cally axis style=red!75!black
to set all the elements belonging to the y axis to that colour.One legend for both axes
Plots directly labeled
Axis colours match plot colours