PGFPlots Annotations – Annotate Triangle with Slope in Axis Environment

annotationspgfplotstikz-pgf

In journal papers, I often see annotations in figures depicting triangles with certain slopes to emphasize which slopes the different graphs in the figure (approximately) have.

For example

Is there a macro in LaTeX to make such annotations easily? So, given a relative position in the axis and a slope, a triangle with this slope is plotted at the relative position in the axis?

Best Answer

% Mind section '4.17 Custom annotations' of the PGFplots manual Revision 1.12 (2015/01/31).
\documentclass[margin=1cm]{standalone}

\usepackage{pgfplots}

\pgfplotsset{compat=newest}

%%% START MACRO %%%
\newcommand{\slopeTriangle}[5]
{
    % #1. Relative offset in x direction.
    % #2. Width in x direction, so xA-xB.
    % #3. Relative offset in y direction.
    % #4. Slope dydx.
    % #5. Plot options.

    \pgfplotsextra
    {
        \pgfkeysgetvalue{/pgfplots/xmin}{\xmin}
        \pgfkeysgetvalue{/pgfplots/xmax}{\xmax}
        \pgfkeysgetvalue{/pgfplots/ymin}{\ymin}
        \pgfkeysgetvalue{/pgfplots/ymax}{\ymax} 

        % Calculate auxilliary quantities.
        \pgfmathsetmacro{\xA}{\xmin+(#1+#2)*(\xmax-\xmin)}
        \pgfmathsetmacro{\yA}{\ymin+#3*(\ymax-\ymin)}
        \pgfmathsetmacro{\xB}{\xmin+#1*(\xmax-\xmin)}
        \pgfmathsetmacro{\yB}{\yA}
        \pgfmathsetmacro{\xC}{\xA}
        \pgfmathsetmacro{\yC}{\yA+(\xA-\xB)*#4}

        % Define coordinates for \draw.
        \coordinate (A) at (axis cs:\xA,\yA);
        \coordinate (B) at (axis cs:\xB,\yB);
        \coordinate (C) at (axis cs:\xC,\yC);

        % Draw slope triangle.
        \draw[#5]   (A)-- node[pos=0.5,anchor=north] {1}
                    (B)-- 
                    (C)-- node[pos=0.5,anchor=west] {#4}
                    cycle;
    }
}
%%% END MACRO %%%

\begin{document}
    \begin{tikzpicture}
        \begin{axis}
        [
            xtick={-0.1,0,1,1.1},
            xlabel=$x$,
            ytick={-0.2,0,2,2.2},
            ylabel style={rotate=-90},
            ylabel=$y$,
            unit vector ratio=2 1 1,
            clip=false
        ]
            \addplot[blue,domain=0:1] {x};
            \addplot[red,domain=0:1] {2*x};

            \slopeTriangle{0.65}{0.1}{0.1}{1}{blue}; % USE OF MACRO.
            \slopeTriangle{0.825}{0.1}{0.1}{2}{red}; % USE OF MACRO.
        \end{axis}
    \end{tikzpicture}
\end{document}