Data Science and Computing with Python for Pilots and Flight Test Engineers
Scatter Plot (Plotting Data Points)
Plotting Data Points in a Scatter Plot
Imagine we have the follow data points:
x | y |
---|---|
0 | 0 |
1 | 1 |
2 | 4 |
3 | 9 |
4 | 16 |
5 | 25 |
This data comes in pairs of \(x\) and \(y\) values. We will plot the data points by plotting the \(x\) values along the horizontal axis and the \(y\) values along the vertical axis.
In order to ingest the data into Python, we will put it into a matrix and then extract the first and second row (of course, we could have put the data into two 1-dimensional arrays to begin with).
Put Data into a Matrix
Let us put the data into a matrix
$$ \mathrm{data} = \begin{pmatrix} 0 & 0 \\ 1 & 1 \\ 2 & 4 \\ 3 & 9 \\ 4 & 16 \\ 5 & 25 \end{pmatrix} $$
import numpy as np # for math
import matplotlib.pyplot as plt # for plotting
# Create a 2-dimensional array containing the input data we want to plot:
data = np.array([[0,0],
[1, 1],
[2, 4],
[3, 9],
[4, 16],
[5, 25]])
Extract the First and Second Column
We can create the two one-dimensional arrays xdata and ydata from the above matrix, extracting the first and second columns, respectively. We do so, because it will be easier later for plotting.
xdata = np.array(data[:,0]) # horizontal data values (values of x)
ydata = np.array(data[:,1]) # vertical data values (values of y)
Plotting the Data
Now plot the data. We just need one line of code for this. The rest are optional extras to make it look nicer. One line saves the plot to a file, so you can use it elsewhere in other documents. Python automatically infers the proper file format for the saved file from the file extension you provide in the filename. You can use .pdf, .jpg, .png, etc. In the example, we have saved the file in the same directory as this notebook file, hence the “./” in front of the filename.
# Now plot the data:
plt.scatter(xdata, ydata, color="blue", label="Data sampled from function $f(x)=x^2$")
# Optional commands for title, axis labels, and legend:
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.title("My First Data Plot")
plt.legend() # plots the label inset into the plot in the upper right corner
plt.savefig("./jupyter_notebook_plot1.pdf") # this optional line saves the plot to a file.
plt.show()
Want to make your own plot of some data? Simply copy and paste the code from the four code cells above into a new Jupyter notebook and change the numbers in the array “data” in the second code cell to whatever data you want to plot. You can also change the color of the dots, axis labels, title, and the legend to whatever suits your needs (or omit them if they are not needed).