有人知道我该如何将图例的位置改为图表的右侧吗?我尝试了很多方法,但都行不通。请帮我一下!这是我的代码!
\resizebox{\textwidth}{!}{
\begin{minipage}{1.3\textwidth}
\begin{center}
\begin{tikzpicture}
\begin{axis}[ /pgf/number format/.cd, use comma, 1000 sep={}, scale only axis, xmin=2006,xmax=2012, ymin=65, ymax=125, axis y line*=left, xlabel=Year, ylabel=\color{black}$Percentage(\%)$]
\addplot[black] coordinates {
%Government Debt
(2006, 68.3608)
(2007, 68.0186)
(2008, 74.963)
(2009, 89.5022)
(2010, 102.7844)
(2011, 114.9962)
(2012, 121.9426)};
\end{axis}
%
\begin{axis}[ scale only axis, xmin=2006,xmax=2012, ymin=-15, ymax=5, axis y line*=right, axis x line=none, ylabel=\color{blue}$Percentage (\%)$]%
\addlegendimage{/pgfplots/refstyle=Hplot}
\addlegendentry{$Debt$}
\addplot[blue, mark=+] coordinates {
%Total Budget Balance
(2006, -1.5862)
(2007, -1.9186)
(2008, -5.624)
(2009, -9.7638)
(2010, -13.0882)
(2011, -8.0618)
(2012, -6.4806)};
\addlegendentry{$TBB$}
%
\addplot[blue,mark=o] coordinates {
%Real per capita GDP growth rate
(2006, 3.7266)
(2007, 3.3016)
(2008, -0.5192)
(2009, -4.1474)
(2010, -0.4744)
(2011, -1.2876)
(2012, -2.4802)
};
\addlegendentry{$GDPpc GR$}
\end{axis}
\end{tikzpicture}
\end{center}
\end{minipage}}
答案1
正如 darthbith 所说,一般来说,您需要添加legend pos=outer north east
将图例放置在右上方轴的外部。在这种情况下,它将与右侧 y 轴上的顶部刻度标签重叠。一个简单的解决方法是也添加legend style={xshift=1em}
,从而将其向右移动一点。
我做的其他更改:
- 在第二个轴上,从 更改
axis y line*=right
为axis y line=right
。后者还会使 ylabel 移动到右侧,考虑到您改变了它的颜色,我认为这是您想要的。 \color{blue}
我添加了而不是ylabel style={blue}
。我认为没有什么大不了的,主要是个人喜好问题。- 不要以数学模式编写标签和图例条目,除非它们是实际的数学变量。
Percentage
例如Debt
,是文本,不应写成数学。
\documentclass[border=3mm]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
/pgf/number format/.cd, use comma,
1000 sep={},
scale only axis,
xmin=2006,
xmax=2012,
ymin=65,
ymax=125,
axis y line*=left,
xlabel=Year,
ylabel=Percentage (\%)]
\addplot[black] coordinates {
%Government Debt
(2006, 68.3608)
(2007, 68.0186)
(2008, 74.963)
(2009, 89.5022)
(2010, 102.7844)
(2011, 114.9962)
(2012, 121.9426)};
\end{axis}
%
\begin{axis}[
scale only axis,
xmin=2006,
xmax=2012,
ymin=-15,
ymax=5,
axis y line=right,
axis x line=none,
ylabel=Percentage (\%),
ylabel style={blue},
yticklabel style={blue},
legend pos=outer north east,
legend style={xshift=1em}]%
\addlegendimage{/pgfplots/refstyle=Hplot}
\addlegendentry{Debt}
\addplot[blue, mark=+] coordinates {
%Total Budget Balance
(2006, -1.5862)
(2007, -1.9186)
(2008, -5.624)
(2009, -9.7638)
(2010, -13.0882)
(2011, -8.0618)
(2012, -6.4806)};
\addlegendentry{TBB}
%
\addplot[blue,mark=o] coordinates {
%Real per capita GDP growth rate
(2006, 3.7266)
(2007, 3.3016)
(2008, -0.5192)
(2009, -4.1474)
(2010, -0.4744)
(2011, -1.2876)
(2012, -2.4802)
};
\addlegendentry{GDPpc GR}
\end{axis}
\end{tikzpicture}
\end{document}