How to use matplotlib to plot a function with the argument on an axis

Viewed 972

I want to plot the function

enter image description here

up to sum finite k. I'll take the t values from the horizontal axis.

What I have so far:

def f_func(n, t):
     summation = sum([np.sin(k*t)/k for k in range(n)])
     return summation

Now that I have the function, I want to tell matplotlib to use it's horizontal axis as the time parameter, while I choose a specific k parameter. How do I go about doing this?

2 Answers

You can call f_func in a loop and place the values in a list. Note that the summation needs to start at k=1 to prevent division by zero.

The following example code creates the curve for successive values of n:

from matplotlib import pyplot as plt
import numpy as np

def f_func(n, t):
    summation = sum([np.sin(k * t) / k for k in range(1, n + 1)])
    return summation

ts = np.linspace(-5, 12.5, 200)
for n in range(1, 11):
    fs = [f_func(n, t) for t in ts]
    plt.plot(ts, fs, label=f'$n={n}$')
plt.margins(x=0, tight=True)
plt.xlabel('$t$')
plt.ylabel('$f(n, t)$')
plt.legend(ncol=2)
plt.show()

example plot

PS: You could play around with numpy's broadcasting and calculate the f-values in one go. The function needs to be adapted a bit, taking sums of columns of an intermediate matrix:

ts = np.linspace(-5, 12.5, 200)
ks = np.arange(1, n+1).reshape(-1, 1)
fs = np.sum(np.sin(ks * ts) / ks, axis=0)
plt.plot(ts, fs, label=f'$n={n}$')

Disclaimer: matplotlib is huge, and I'm skipping a ton of details that probably don't matter right now.

In matplotlib, you don't use a horizontal axis as the time parameter; you define the horizontal axis, you define the vertical axis, and if there's supposed to be a relationship between those you need to take care to explicitly code it.

def f_func(n, t):
    k = np.arange(1, n)  # none of that pesky division by 0
    return np.sum(np.sin(t*k)/k)

# This will be our horizontal axis; use whichever
# t-values you want. We're using [0,1,...,99] 
# as an example.
horizontal = np.arange(100)

# Corresponds exactly to how many terms of
# the summation you're considering.
n = 42

# Using the horizontal axis as the time parameter is
# accomplished by explicitly creating the horizontal
# axis as the time parameter (which we've already
# done) and ensuring the vertical axis uses the
# function we want to plot.
vertical = [f_func(n, t) for t in horizontal]

# Actual plotting stuff. Tweak as needed.
plt.plot(horizontal, vertical)
plt.show()
Related