如何在 pgfplot Y 轴最大值上方添加节点?

如何在 pgfplot Y 轴最大值上方添加节点?

我想在 pgfplots 中 Y 轴最大值上方添加一些节点(标签)。我得到了以下 MWE:

\documentclass{beamer}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{positioning,fit}

\begin{document}
\begin{frame}
  \frametitle{TEST}
  \centering
  \begin{tikzpicture}
    \begin{axis}[xlabel=Cost,ylabel=Gain]
      \addplot[color=red,mark=x] coordinates { (10,100) (20,150) (40,225) (80,340) (160,510) (320,765) (640,1150) };
      \node at (axis cs:0,1200) [rotate=90, anchor=west] {Label 0};
      \node at (axis cs:200,1200) [rotate=90, anchor=west] {Label 200};
      \node at (axis cs:400,1200) [rotate=90, anchor=west] {Label 400};
      \node at (axis cs:600,1200) [rotate=90, anchor=west] {Label 600};
    \end{axis}
  \end{tikzpicture}
\end{frame}

\begin{frame}
  \frametitle{TEST}
  \centering
  \begin{tikzpicture}
    \begin{axis}[xlabel=Cost,ylabel=Gain, ymax=2000]
      \addplot[color=red,mark=x] coordinates { (10,100) (20,150) (40,225) (80,340) (160,510) (320,765) (640,1150) };
      \node at (axis cs:0,1200) [rotate=90, anchor=west] {Label 0};
      \node at (axis cs:200,1200) [rotate=90, anchor=west] {Label 200};
      \node at (axis cs:400,1200) [rotate=90, anchor=west] {Label 400};
      \node at (axis cs:600,1200) [rotate=90, anchor=west] {Label 600};
    \end{axis}
  \end{tikzpicture}
\end{frame}

\end{document}

在第一个解决方案中,标签不可见。在第二个解决方案中,它们是可见的,但我真的想将 Y 轴“停止”在 1200 和 2000。我怎么才能得到这样的图?我想我应该在环境之外的图上画出来axis,不是吗?

答案1

您需要添加clip=falseaxis选项中,默认情况下,在轴限制之外绘制的所有内容都会被剪掉。

\documentclass{beamer}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{positioning,fit}

\begin{document}
\begin{frame}
  \frametitle{TEST}
  \centering
  \begin{tikzpicture}
    \begin{axis}[xlabel=Cost,ylabel=Gain,clip=false,ymin=0,ymax=1200]
      \addplot[color=red,mark=x] coordinates { (10,100) (20,150) (40,225) (80,340) (160,510) (320,765) (640,1150) };
      \node at (axis cs:0,1200) [rotate=90, anchor=west] {Label 0};
      \node at (axis cs:200,1200) [rotate=90, anchor=west] {Label 200};
      \node at (axis cs:400,1200) [rotate=90, anchor=west] {Label 400};
      \node at (axis cs:600,1200) [rotate=90, anchor=west] {Label 600};
    \end{axis}
  \end{tikzpicture}
\end{frame}
\end{document}

相关内容