# How to shorten the length of the tangent line

I have all the equations down to manipulate the tangent line on the graph... but the tangent line is too long, what would be the best way to shorten it?

f[x_] = Sin[x];

Plot[f[x], {x, -2 Pi, 2 Pi}]

tangent[f_, a_, x_] := f'[a] (x - a) + f[a]

Manipulate[Plot[{f[x], tangent[f, p, x]}, {x, -2 Pi, 2 Pi}, Epilog -> {Red, PointSize[.015], Point@{p, Sin[p]}}], {p, -Pi, Pi}]


This is a kludge onto your code. I would have written the whole thing rather differently.

Manipulate[
Plot[
{f[x], If[Abs[p - x] < 1, 100 tangent[f, p, x], 0]},
{x, -2 Pi, 2 Pi},
Epilog -> {Red, PointSize[.015], Point@{p, Sin[p]}}],
{p, -Pi, Pi}]


• You could replace the 0 by Indeterminate or Undefined in the If[] statement to eliminate the line along the x axis. Is the factor of 100 a typo, perhaps? Commented Sep 19, 2019 at 13:23

You can use ConditionalExpression as in this answer linked by m_goldberg in comments:

Manipulate[
Plot[{f[x], ConditionalExpression[tangent[f, p, x], p - .5 <= x <= p + .5]},
{x, -2 Pi, 2 Pi},
Epilog -> {Red, PointSize[.015], Point@{p, Sin[p]}}], {p, -Pi, Pi}]


You can replace ConditionalExpression[...] with

Piecewise[{{tangent[f, p, x],  p - .5 <= x <= p + .5}}, Undefined]


to get the same result.