凡例を外側に配置してプロットを中央に配置する方法

凡例を外側に配置してプロットを中央に配置する方法

外側の凡例のあるプロットを中央に配置したいのですが、図全体が中央に配置されてしまいます (凡例のあるプロット)。プロットの位置は、外側の凡例が存在しないような位置である必要があります。

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepackage{tikz}

\begin{document}

\begin{figure}[h]
\centering
  \begin{tikzpicture}
  \begin{semilogxaxis}[
  xmin=0.01,xmax=100,
  ymin=0,ymax=5,
  width=8cm,
  legend style={at={(1.03,0.5)},anchor=west,draw=none},
  legend cell align={left},
  grid]
  \addplot[red,domain=0.01:100,samples=400]{(2)/(1+x^2)};
  \addplot[blue,domain=0.01:100,samples=400]{(1+x^2)/(1-x^2+x^4)};
  \legend{$Q=0.5$,$Q=1$}
  \end{semilogxaxis}
  \end{tikzpicture}
\caption{Lorem Ipsum}
\end{figure}

\end{document}

次のようになります: ここに画像の説明を入力してください

ただし、次のようになります (もちろん、外側の凡例が追加されます)。 ここに画像の説明を入力してください

答え1

おそらく、希望どおりの結果を得るための最も簡単な方法は、オプションoverlayを追加することだと思いますlegend style。これにより、凡例が境界ボックスの決定に考慮されなくなります。

% used PGFPlots v1.16
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}[h]
    \centering
    \begin{tikzpicture}
        \begin{semilogxaxis}[
            xmin=0.01,xmax=100,
            ymin=0,ymax=5,
            width=8cm,
            legend style={
                overlay,        % <-- added
                at={(1.03,0.5)},
                anchor=west,
                draw=none,
            },
            legend cell align={left},
            grid,
            domain=0.01:100,samples=400,
        ]
            \addplot [red]  {(2)/(1+x^2)};
            \addplot [blue] {(1+x^2)/(1-x^2+x^4)};
            \legend{$Q=0.5$,$Q=1$}
        \end{semilogxaxis}
    \end{tikzpicture}
    \caption{Lorem Ipsum}
\end{figure}
\end{document}

上記コードの結果を示す画像

答え2

以下のものをお探しですか?

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

(赤い線はテキストの境界線を示します)

tikzpictureこのためには、オプションに以下を追加するだけですtrim axis left, trim axis right:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}

%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%

\begin{document}
    \begin{figure}[ht]
\centering
  \begin{tikzpicture}[trim axis left, trim axis right] % <-------
  \begin{semilogxaxis}[
  xmin=0.01,xmax=100,
  ymin=0,ymax=5,
  width=8cm,
  legend style={at={(1.03,0.5)},anchor=west,draw=none},
  legend cell align={left},
  grid]
  \addplot[red,domain=0.01:100,samples=400]{(2)/(1+x^2)};
  \addplot[blue,domain=0.01:100,samples=400]{(1+x^2)/(1-x^2+x^4)};
  \legend{$Q=0.5{}$,$Q=1$}
  \end{semilogxaxis}
  \end{tikzpicture}
\caption{Lorem Ipsum}
    \end{figure}
\end{document}

関連情報