Lab 02 - Curlss/Computational_physics GitHub Wiki
In Lab 02, the goal was to introduce you to basic plotting and visualization functions. In this lab, matplotlib was essential, and so was numpy, although numpy is much more common than matplotlib, but in order to plot anything onto a graph, you need it in your module. This lab was broken up into learning about how a modulo(%) function works, reading data off a file, as well as being able to plot it and creating visualization plots. For the visualization plots, we were to create kinds of plots such as a polar plot, displaying an image, creating a line of best fit with data, histogram of data, a multipanel plot, and a 3D plot.
In the first section of the lab, we learned what modulo(%) does for you in a function, which returns the remainder of the division problem. We created a function to indicate when a number is even and when it's odd, as well as made sure it would justify that if you type letters, it will tell you to enter a number. Code example
def oddeven(n):
if type(n) != int: #!= means not equal too
print('not a number, enter an number')
elif n % 2 == 0: # == means equal too
print("its even")
else:
print("that's odd...")
oddeven(5)
oddeven(4)
oddeven('h')
In the next section, you were given data in a file and needed to be able to plot it. In the data, we needed to download the data, which we used wget, and then we needed the code to read the data, so we used np.loadtxt, which takes it in and then assign a variable for the data. The data has two columns, so we set the first one to be the temperature and the second column to be the magnitude in the code that will be shown. We then created a plot with certain x and y ranges on the graph, inverted x-axis, and y-axis, as well as created labels for specific points of the graph. We added alpha into our main plt.plot to control how clearly you can see the stars more individually than when running it; you can adjust the alpha number from 0-1. After creating this graph, we created another one using the same features, just with the scatter plot method, which is plt.scatter(x,y,c=color) We did our color by the temperature of the star. Here is our example for the first graph:
star_data = np.loadtxt('stars.txt')
# set the first column equal to temp in Kelvin
temp = star_data[:,0]
# set the second column equal to magnitude
mag = star_data[:,1]
# open a figure
plt.figure(figsize=(7,6))
# use the plt.plot command to plot magnitude versus temperature
# plot the points using blue stars
# set alpha=.2 so you can see the points better
plt.plot(temp,mag,'b*',alpha = .4) #it was blury @ .2 so i went up closer to one
# limit the x range uto (0,13000) using plt.xlim()
plt.xlim(0,13000)
# limit the x range uto (-5,20) using plt.ylim()
plt.ylim(-5,20)
# invert the x axis so that high lumonisities are on the left
ax = plt.gca()
ax.invert_xaxis()
# invert the y axis because magnitudes are weird in that
# brighter objects have lower magnitudes
ax.invert_yaxis()
# label your x and y axis
plt.xlabel('Temperature (K)')
plt.ylabel('Magnitude')
# the sequence in the lower left is white dwarfs
# add a text label to show where the white dwarfs are
# using plt.text() (use help(plt.text) to learn how to use it.)
plt.text(10500,15,'White Dwarfs')
# the sequence around T=5000 and magnitude=0 are giants
# Add a label to show where the giants are using plt.text()
plt.text(5000,0,' Giants')
In the following section, we were given an example of how to create a polar plot we just needed to fill in, creating an array of radial values and angles. For the next example, we were given half the code to create a polar plot of the sine and cosine of theta with some of the code being there; I just made r be sintheta and r2 be cosinetheta having the plot be in polar it needs to have subplot_kw = {'projection':'polar'} this create the graph to be polar. Here is the code for this example:
# let theta range from zero to 2 pi, with 200 steps
theta = np.linspace(0,2*np.pi,200)
r = np.sin(theta)
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'},figsize=(6,6))
ax.plot(theta, r)
# enter code to plot cos(theta)
r2 = np.cos(theta)
ax.plot(theta,r2)
ax.set_rticks([0.25, .5, .75,1]) # Less radial ticks
ax.grid(True)
This next section was to learn how to display an image using matplotlib. Using !wegt to download the file, it is a Linux command, and then using image.imread(image name) to display the image; you can also do it with Google, where you have to import a module for Google colab, which is from google.colab import files then you have to upload = files.upload() so you can choose a file or import a downloaded image from Google. To show any image, you must print it, and you can do that with plt.imshow(); that is where you create a variable(X) for your image.imread(file name) to make it easier to print. Here is one way the code can look:
from google.colab import files
uploaded = files.upload() #import a file downloaded from your computer
myimagae= image.imread('cute future puppy.jpeg')
plt.imshow(myimagae)
For the next two sections in the lab, we were to fill in some parts of the code to create a line of best fit and a histogram. In the line of best fit, one of the most important lines in the code is using np.polyfit; it is what creates the line of best fit itself. The histogram code was also given as a filling in some of the code; we were introduced to np.random.normal(), which generates a random normal distribution in this code, we are generating 1500 and creating it into a histogram which to do so you must have plt.hist(). For the histogram, we added visual lines to see the average of the numbers and two other dotted lines of the average + standard deviation and average - standard deviation. This is the code to creating the line of best fit:
data = np.loadtxt('millikan.txt')
#set the first column equal to frequency(Hz)
freq = data[:,0]
#set the second column equal to volt(V)
volt = data[:,1]
#create a line of best fit with the data using np.polyfit
c=np.polyfit(freq,volt,1)
xline= np.linspace(min(freq),max(freq),100)
yline= np.polyval(c,xline)
plt.plot(freq,volt,'ko')
plt.plot(xline,yline,'r')
print(f'planck constant = {c[0] * 1.6*10**(-19)}')
print(f'work function = {c[1]}')
And this is the histogram:
plt.figure(figsize=(8,6))
gauss_values = np.random.normal(size=1500)
plt.hist(gauss_values)
print("average value = {:.2f}".format(np.mean(gauss_values)))
print("the STD = {:.2f}".format(np.std(gauss_values)))
# add code to plot a solid vertical line at the average
# you can pick the color, but it should be different from the histogram
# use plt.axvline()
plt.axvline(np.mean(gauss_values),color='green')
# add code to plot dotted vertical lines at
# you can pick the color, but it should be different from the histogram
# average + std
# average - std
plt.axvline(np.mean(gauss_values)+np.std(gauss_values),color='black',linestyle='--')
plt.axvline(np.mean(gauss_values)-np.std(gauss_values),color='red',linestyle='--')
# once your figure is set, try increasing the sample size
# what happens to the mean and std as the sample size increases?
print('As the sample size increases the mean and std being to get closer to the normal distribution ')
The last three sections teach you how to create different kinds of plots, such as Multipanel plotting and 3D plotting, and then create a plot of your interest. Creating a Mutipanel plot is very easy; you use plt.subplot(nrow,ncol,nplot), which displaces where the graph will be located when looking at it, meaning there could be a total of two rows and two columns, meaning that it's 2x2, which it can only contain four graphs and you can set up the plt.plot how you would set up every other. This is the code example for a multipanel plot:
theta = np.linspace(0,2*np.pi,100)
plt.subplots_adjust(wspace=0.5, hspace=0.5)
#1
plt.subplot(2,2,1)
plt.plot(theta,np.sin(theta),'b')
plt.title('sin(theta)')
#2
plt.subplot(2,2,2)
plt.plot(theta,np.cos(theta),'r')
plt.title('cos(theta)')
#3
plt.subplot(2,2,3)
plt.plot(theta,np.tan(theta),'g')
plt.title('tan(theta)')
#4
plt.subplot(2,2,4)
plt.plot(theta,np.sin(theta),'b')
plt.plot(theta,np.cos(theta),'r')
plt.plot(theta,np.tan(theta),'g')
plt.title('all three functions')
Creating a 3D plot, you must have plt.axes(projection ='3d') so that it creates and the plt.axes is how it's trying to place its axes so when putting the projection 3d its having the graph create its axes in 3d format. This is the code to create a swirl in 3d:
fig = plt.figure()
# keeping the projection = 3d
# ctreates the 3d plot
ax = plt.axes(projection = '3d')
time = np.linspace(0,10)
x = np.cos(time)
y = np.sin(time)
plt.plot(x,y,time)
# add your title here!
plt.title('3D image of a swirly slide ')
This last one was a plot of my choice, I saw on matplotlib website different patterns, and one that caught my eye was creating a Delaunay triangulation, i thought it looked cool so I replicated the code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as tri
# First create the x and y coordinates of the points.
num_angles = 36
num_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, num_radii)
angles = np.linspace(0, 2 * np.pi, num_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], num_radii, axis=1)
angles[:, 1::2] += np.pi / num_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1)) < min_radius)
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
ax1.triplot(triang, 'yo-', lw=2)
ax1.set_title('triplot of Delaunay triangulation')