我正在使用手动绘制的矩形来绘制图表,而不是使用 PGFPlots 中定义的标准图表类型。这是 MWE:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xmin=0,xmax=5,ymin=0,ymax=4]
\draw[fill=blue!50] (0,0) rectangle (1,1);
\draw[fill=green!50] (1,0) rectangle (4,3);
\draw[fill=red!50] (4,0) rectangle (5,2);
\end{axis}
\end{tikzpicture}
\end{document}
问题: 如何在图中添加图例?我想给三个矩形分别贴上标签,例如,矩形 1 为“蓝色”,矩形 2 为“绿色”,矩形 3 为“红色”。
答案1
您可以使用\addlegendimage
:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xmin=0,xmax=5,ymin=0,ymax=4]
\draw[fill=blue!50] (0,0) rectangle (1,1);
\draw[fill=green!50] (1,0) rectangle (4,3);
\draw[fill=red!50] (4,0) rectangle (5,2);
\addlegendimage{area legend, fill=blue!50}
\addlegendimage{area legend, fill=green!50}
\addlegendimage{area legend, fill=red!50}
\legend{foo, bar, baz}
\end{axis}
\end{tikzpicture}
\end{document}
答案2
像这样吗?
- 如果我正确理解了你的问题的话,因为我使用了
tikz
,因为你并不真正需要。pgfplots
- 在提供图例的节点中,我使用了两个不同的元素......
代码
\documentclass[11pt, border=1cm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[blue, fill=blue!50] (0, 0) rectangle (1, 1);
\draw[green, fill=green!50] (1, 0) rectangle (4, 3);
\draw[red, fill=red!50] (4, 0) rectangle (5, 2);
% the legend
\path (5, 5) node[draw, scale=.6, anchor=north west, text width=4.4em]
{%
$1$ = blue
$2$ = green
$3$ = \tikz{\draw[red, fill=red!50] (0, 0) rectangle (1em, 1.5ex);}
};
% the axes
\draw[->] (0, 0) -- (6, 0) node[below, scale=.8] {$x$};
\draw[->] (0, 0) -- (0, 5) node[left, scale=.8] {$y$};
\foreach \i in {1, ..., 5}{
\draw (\i, 2pt) -- ++(0, -4pt) node[below, scale=.7] {$\i$};
}
\foreach \j in {1, ..., 4}{
\draw (2pt, \j) -- ++(-4pt, 0) node[left, scale=.7] {$\j$};
}
\end{tikzpicture}
\end{document}
答案3
这使用保存框内的表格来构建图例。
请注意,人们确实应该\sbox0
在环境或组内保存其全局内容。
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\sbox0{\begin{tabular}{rl}
\tikz{\node [fill=blue!50, inner sep=1ex]{};} & blue\\
\tikz{\node [fill=green!50, inner sep=1ex]{};} & green\\
\tikz{\node [fill=red!50, inner sep=1ex]{};} & red
\end{tabular}}
\begin{tikzpicture}
\begin{axis}[xmin=0,xmax=5,ymin=0,ymax=4,name=border]
\draw[fill=blue!50] (0,0) rectangle (1,1);
\draw[fill=green!50] (1,0) rectangle (4,3);
\draw[fill=red!50] (4,0) rectangle (5,2);
\end{axis}
\node[below=1cm, draw, rounded corners] at (border.south) {\usebox0};
\end{tikzpicture}
\end{document}