PGFplots の凡例を軸とぴったり一致するように上部揃えにする方法

PGFplots の凡例を軸とぴったり一致するように上部揃えにする方法

私の目標は、凡例ボックスをプロットの上部に揃えて、上部の軸フレームとぴったり一致するようにすることです。

次の MWE は一見すると問題なく動作しますが、よく見ると、小さな垂直オフセットがあります (画像を参照)。一度見たら、忘れることはできません。

\documentclass[tikz,margin=10pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        legend style={
            legend pos=outer north east
        }
    ]
    \addplot[color=gray!50,mark=x] coordinates {
        (1,1)
    };
    \addlegendentry{Stuff}
    \addplot[color=gray,mark=x] coordinates {
        (2,2)
    };
    \addlegendentry{Other stuff}
    \end{axis}
\end{tikzpicture}
\end{document}

軸と凡例ボックス間の予期しないオフセットの例

他の回答から、凡例は TikZ マトリックスであることを知っています。座標 (軸 cs など) を使用して凡例を配置できることは認識しています。ただし、次のようにハードコードされた配置を使用する場合でも、境界線は正確に揃いません。

    \begin{axis}[
        legend style={
            at={(axis cs:2.6,2.1)}
        },
        ymax=2.1
    ]

関連がある場合、私は TeX Live 2019 インストールを使用しています。

答え1

TeX.SE へようこそ。outer sep = 0pt凡例スタイルを追加することが適切な解決策になるかもしれません。

凡例をキャンバスの境界と同じ高さに配置し、outer sep=0ptスタイルに追加されたときにキャンバスの上部と凡例が揃っていることを示唆するコードを追加しました。

\documentclass[tikz,margin=10pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        legend style={
            outer sep=0pt,
            legend pos=outer north east
        }
%        legend style={
%        anchor=north west,
%        outer sep=0pt,
%        at= {(current axis.north east)},
%}
    ]
    \addplot[color=gray!50,mark=x] coordinates {
        (1,1)
    };
    \addlegendentry{Stuff}
    \addplot[color=gray,mark=x] coordinates {
        (2,2)
    };
    \addlegendentry{Other stuff}
    \end{axis}
\end{tikzpicture}
\end{document}

ここに画像の説明を入力してください

関連情報