Data Science and Computing with Python for Pilots and Flight Test Engineers
Function Plot (Plotting a Mathematical Function)
In the previous lesson, we were given some data points to plot. In this lesson we will plot a mathematical function given by a formula. As an example, let us choose the following function given by equation:
$$ y = f(x) = a x^b $$
where \(a\) and \(b\) are fixed parameters, whereas \(x\) is the variable which we plot along the horizontal axis. Along the vertical axis we plot the values of the function \(f(x)\).
For illustration, we plot the function with two different values for the parameters \(a\) and \(b\). For the second curve, we also include a legend in the plot which automatically indicates the values of the parameters.
import numpy as np
import matplotlib.pyplot as plt
# Define the function we wish to plot (x shall be the variable of the function, a and b its fixed parameters):
def function1(x, a, b):
y = a * x**b
return y
Now we plot this function. Note that for matplotlib to be able to plot the function it must first be sampled at many points in order to create a smoothly looking plot. This is achieved by the linspace function at the beginning, which creates such a sample set along the horizontal axis.
# Make a new plot of two functions:
x = np.linspace(0, 10, 1000) # creates 1000 sample points, between x=0 and x=10, where the function will be evaluated for plotting.
a = 1.0
b = 2.5
y = function1(x, a, b) # assigns the values of the function at points x to the variable y.
plt.plot(x, y, "r-") # plots the function (i.e. x versus y) in red, connecting the sample points (that's what "r-" means).
plt.show()
We can also add labels to this plot, show the values of parameters $a$ and $b$ automatically in the legend, and save the plot to a file:
x = np.linspace(0, 10, 1000) # creates 1000 sample points, between x=0 and x=10, where the function will be evaluated for plotting.
a = 1.0
b = 2.0
y = function1(x, a, b)
plt.plot(x, y, "b-", label=('$f(x)=ax^b$ with a=%3.1f and b=%3.1f' %tuple([a, b])) )
# Optional commands for title, axis labels, and legend:
plt.xlabel("x")
plt.ylabel("y=f(x)")
plt.title("A Plot of a Function")
plt.legend() # plots the label inset into the plot in the upper right corner
plt.savefig("./jupyter_notebook_plot2.jpg") # saves the plot to a JPEG file in the same directory as the Jupyter notebook file. The file extension tells Python automatically, in which file format the figure is to be saved. pdf, jpg, and png are common good options.
plt.show()
Copy and paste the above code cells into your Jupyter notebook on your computer and evaluate them, to see the plots. After running the code, you should also find a file jupyter_notebook_plot2.jpg in the same directory as your Jupyter notebook file.