[Tex/LaTex] How to draw tangent line of an arbitrary point on a path in TikZ

asymptotemetapostpstrickstikz-pgf

Suppose I specify some node as occurring at some point on a path. Say for example the node (P) defined on the following path.

\path[draw] (0,9) to[out=-90,in=180] (9,0) node[pos=0.7,circle] (P) {};

I would now like to draw the tangent line at (P) to indicate the slope of the curve at that point.

Best Answer

Here's an approach that uses the decorations.markings library to place support coordinates at a specified distance along a path, which can be used to set a local coordinate system at a later time to draw tangents or orthogonal lines.

You specify a tangent point by using tangent=<pos> in your first path. In a later path, you can then set use tangent to set a local coordinate system for that path: (0,0) is the tangent point itself, (1,0) is 1 unit along the tangent line, (0,1) is one unit along the orthogonal line.

You can specify tangent=<pos> multiple times in your original path. You can then specify which tangent point to use for a new path by calling use tangent=<count>, where the tangent points are numbered in the order they were specified in the original path.

Using these styles, the following code

\draw [
    tangent=0.4,
    tangent=0.56
] (0,0)
    to [out=20,in=120] (5,2)
    to [out=-60, in=110] (9,1);
\draw [blue, thick, use tangent] (-3,0) -- (3,0);
\draw [orange, thick, use tangent=2] (-2,0) -- (2,0) (0,0) -- (0,1);

would yield this


Here's the complete code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}

\begin{document}

\begin{tikzpicture}[
    tangent/.style={
        decoration={
            markings,% switch on markings
            mark=
                at position #1
                with
                {
                    \coordinate (tangent point-\pgfkeysvalueof{/pgf/decoration/mark info/sequence number}) at (0pt,0pt);
                    \coordinate (tangent unit vector-\pgfkeysvalueof{/pgf/decoration/mark info/sequence number}) at (1,0pt);
                    \coordinate (tangent orthogonal unit vector-\pgfkeysvalueof{/pgf/decoration/mark info/sequence number}) at (0pt,1);
                }
        },
        postaction=decorate
    },
    use tangent/.style={
        shift=(tangent point-#1),
        x=(tangent unit vector-#1),
        y=(tangent orthogonal unit vector-#1)
    },
    use tangent/.default=1
]
\draw [
    tangent=0.4,
    tangent=0.56
] (0,0)
    to [out=20,in=120] (5,2)
    to [out=-60, in=110] (9,1);
\draw [blue, thick, use tangent] (-3,0) -- (3,0);
\draw [orange, thick, use tangent=2] (-2,0) -- (2,0) (0,0) -- (0,1);
\end{tikzpicture}
\end{document}