如何在 pgfplots 中的两个轴坐标上垂直放置图例?

如何在 pgfplots 中的两个轴坐标上垂直放置图例?

我有使用此代码生成的双轴图。

\documentclass[tikz]{standalone}

\usepackage{pgfplots}
%\pgfplotsset{compat=1.14}
%\pgfplotsset{compat=1.3} % also works for me
\pgfplotsset{compat=1.8} % also works for me

\begin{document}

%% Taken from the pgfplots manual
% Revision 1.15 (2017/06/05)
% 4.9.11 Two Ordinates (y-axis) or Multiple Axes

\begin{tikzpicture}
% let both axes use the same layers
\pgfplotsset{set layers}
%
\begin{axis}[
scale only axis,
xmin=-5,xmax=5,
axis y line*=left,
xlabel=$x$,
ylabel style = {align=center},
ylabel={Plot 1},
legend style={at={(axis description cs:0,0.92)},anchor=west},
]
\addplot {x^2};
\addlegendentry{Blue}
\end{axis}
%
\begin{axis}[
scale only axis,
xmin=-5,xmax=5,
axis y line*=right,
axis x line=none,
ylabel style = {align=center},
ylabel={Plot 2},
]
\addplot [red] {3*x};
\addlegendentry{Red}
\addplot [black] {1*x};
\addlegendentry{Black}
\end{axis}
%
\end{tikzpicture}

\end{document}

生成以下图表

在此处输入图片描述

我想将图例垂直移动到 y 轴,以便清楚地知道哪个轴对应于哪个图形。

用油漆将它画成类似这样。

在此处输入图片描述

答案1

这里建议使用\label\ref来表示图例中的小图像。

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
%\pgfplotsset{compat=1.3} % also works for me
%\pgfplotsset{compat=1.8} % also works for me

\begin{document}

\begin{tikzpicture}
\tikzset{
  legendmatrix/.style={% style for legends
    draw,% draw a border for the legend
    outer sep=.3333em,% additional space to the axis label
    nodes={rotate=90,anchor=base west,outer sep=0pt},% rotate the nodes inside the matrix
    /pgfplots/every crossref picture/.append style={rotate=90,yshift=.75ex}% rotate the legend images
  }
}
\pgfplotsset{% settings for both axises
  scale only axis,
  xmin=-5,xmax=5
}
\begin{axis}[
    axis y line*=left,
    xlabel=$x$,
    ylabel style = {name=ylabel1},% name the ylabel to position the legend
    ylabel={Plot 1}
  ]
  \addplot {x^2};\label{plot:plot1_blue}
\end{axis}
\matrix[legendmatrix,at={(ylabel1.north)},anchor=east]{% legend for Plot 1
  \node{Blue};         \\
  \ref{plot:plot1_blue}\\
};
%
\begin{axis}[
    axis y line*=right,
    axis x line=none,
    ylabel style = {name=ylabel2},% name the ylabel to position the legend
    ylabel={Plot 2}
  ]
  \addplot [red] {3*x};\label{plot:plot2_red}
  \addplot [black] {1*x};\label{plot:plot2_black}
\end{axis}
\matrix[legendmatrix,at={(ylabel2.south)},anchor=west]{% legend for Plot 2
  \node{Red};         &\node{Black};         \\
  \ref{plot:plot2_red}&\ref{plot:plot2_black}\\
};
%
\end{tikzpicture}
\end{document}

结果:

在此处输入图片描述

相关内容