我有一个条形图,每个组上方有三个图例,我想将它们对齐。第一个图例应在左侧,第二个在中间,第三个在右侧。我分别将每个锚点设置为西南、南和东南。所有图例似乎都向左偏移。相反,我希望左侧图例的边缘与 y 轴的左边缘对齐,右侧图例的右边缘与 y 轴的右边缘对齐。中间的图例应该正好在中间。
\documentclass[tikz,crop,margin=0.5cm]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
height=8cm,
width=0.9\textwidth,
bar width=0.5cm,
enlarge x limits=0.25,
major x tick style=transparent,
symbolic x coords={Question 1, Question 2, Question 3},
xtick=data,
ybar=2\pgflinewidth,
ylabel={Count},
ymajorgrids=true,
ymax=20,
ymin=0,
ytick distance=2,
]
\addplot[style={blue, fill=blue, mark=none, label=p1}]
coordinates {(Question 1, 18) (Question 2, 16) (Question 3, 12)};
\label{p1}
\addplot[style={red, fill=red, mark=none}]
coordinates {(Question 1, 2) (Question 2, 4) (Question 3, 8)};
\label{p2}
\end{axis}
\node [draw, fill=white, anchor=south west] at (rel axis cs: 0, 1.05) {
\shortstack[l] {
\underline{Question 1} \\
\ref{p1} Yea \\
\ref{p2} Nay
}
};
\node [draw, fill=white, anchor=south] at (rel axis cs: 0.5, 1.05) {
\shortstack[l] {
\underline{Question 2} \\
\ref{p1} Right \\
\ref{p2} Wrong
}
};
\node [draw, fill=white, anchor=south east] at (rel axis cs: 1, 1.05) {
\shortstack[l] {
\underline{Question 3} \\
\ref{p1} Agree \\
\ref{p2} Disagree
}
};
\end{tikzpicture}
\end{document}
答案1
您可以移动环境内的图例axis
并进行设置clip = false
。
\documentclass[tikz,crop,margin=0.5cm]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
height=8cm,
width=0.9\textwidth,
bar width=0.5cm,
enlarge x limits=0.25,
major x tick style=transparent,
symbolic x coords={Question 1, Question 2, Question 3},
xtick=data,
ybar=2\pgflinewidth,
ylabel={Count},
ymajorgrids=true,
ymax=20,
ymin=0,
ytick distance=2,
clip = false
]
\addplot[style={blue, fill=blue, mark=none, label=p1}]
coordinates {(Question 1, 18) (Question 2, 16) (Question 3, 12)};
\label{p1}
\addplot[style={red, fill=red, mark=none}]
coordinates {(Question 1, 2) (Question 2, 4) (Question 3, 8)};
\label{p2}
\node [draw, fill=white, anchor=south west] at (rel axis cs: 0, 1.05) {
\shortstack[l] {
\underline{Question 1} \\
\ref{p1} Yea \\
\ref{p2} Nay
}
};
\node [draw, fill=white, anchor=south] at (rel axis cs: 0.5, 1.05) {
\shortstack[l] {
\underline{Question 2} \\
\ref{p1} Right \\
\ref{p2} Wrong
}
};
\node [draw, fill=white, anchor=south east] at (rel axis cs: 1, 1.05) {
\shortstack[l] {
\underline{Question 3} \\
\ref{p1} Agree \\
\ref{p2} Disagree
}
};
\end{axis}
\end{tikzpicture}
\end{document}