Home > Enterprise >  Why are the tangent lines from this different lengths
Why are the tangent lines from this different lengths

Time:07-21

I am trying to make a plot of a particular function (decaying sine, but could be anything), and at a particular point, show a bar for the gradient. Or, in fact, at a couple of points, show these bars.

However, the result I am getting is that the bars are different lengths.

Here's the setup:

# create a decaying sinewave, 8 cycles with decaying amplitude
t = np.linspace(0, 8, 1000)
decaying_sine = np.sin(t * np.pi) * np.exp(-t * np.pi / 4)
plt.plot(t, decaying_sine)
plt.show()

Decaying sinewave plot

I then try to superimpose a few slope lines:

def plot_graph_tangent_at_time(graph, t, t_index, label='slope'):
    # Get the slope of graph at that location
    slope = np.gradient(graph, t)[t_index]
    tangent = np.arctan(1/slope)
    line_length = 1
    line_w = np.sin(tangent) * line_length
    line_h = np.cos(tangent) * line_length

    # Add a line to the graph
    plt.scatter(t[t_index], graph[t_index], color='C1', linewidth=2)
    plt.plot([t[t_index] - line_w, t[t_index]   line_w], [graph[t_index] - line_h, graph[t_index]   line_h], 'C1--', label=label)

I then plot this (put these before plt.legend/plt.show):

plot_graph_tangent_at_time(decaying_sine, t, 100)
plot_graph_tangent_at_time(decaying_sine, t, 165)
plot_graph_tangent_at_time(decaying_sine, t, 500)
plot_graph_tangent_at_time(decaying_sine, t, 700)

decaying sinewave with tangent bars

These tangent bars are in the right location, with the right slope - but their lengths are all odd. I tried adding:

    # recalculate the length of the line
    line_length = np.sqrt(line_w**2   line_h**2)
    print(line_length)

In the function, but this printed 1. Technically, I expect the bars to be 2 units long since I double them. Why are these lines different lengths?

CodePudding user response:

The scales of the x and y axes are not the same. Add plt.axis('equal') to your script if you want the lengths of the line segments to appear the same in the plot.

  • Related