![如何在 pgfplots 中的两个轴坐标上垂直放置图例?](https://linux22.com/image/357431/%E5%A6%82%E4%BD%95%E5%9C%A8%20pgfplots%20%E4%B8%AD%E7%9A%84%E4%B8%A4%E4%B8%AA%E8%BD%B4%E5%9D%90%E6%A0%87%E4%B8%8A%E5%9E%82%E7%9B%B4%E6%94%BE%E7%BD%AE%E5%9B%BE%E4%BE%8B%EF%BC%9F.png)
我有使用此代码生成的双轴图。
\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}
结果: