<jupyter_start><jupyter_text>Plotting and Functions This notebook will work trough how to plot data and how to define functions. Throughout the lecture we will take a few moments to plot different functions and see how they depend on their parameters  Plotting in Python: Matplot<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
import scipy as sp<jupyter_output><empty_output><jupyter_text>Pyplot is a powerful plotting library that can be used to make publication quaility plots. It is also useful for quikly plotting the results of a calcualtion. This is a quick demonstration of its useNote: when you call al library `import matplotlib.pyplot as plt` the way that use it is to do the following `plt.function()` where `function()` is whatever you are trying to call from the library<jupyter_code># Define x and y values for some function
x = [i for i in range(20)]
y1 = [i**2 for i in x]
y2 = [i**3 for i in x]<jupyter_output><empty_output><jupyter_text>The methods used above to make the lists is considered very *pythonic*. It works the same as a loop, but outputs all the results into a list. The left-hand most argument is what the list elements will be and the right hand side is the the way the loop will work. When you use pyplot to make a plot, you can add more than one data set to the figure until you render the plot. Once you render the plot it resets<jupyter_code>plt.plot(x,y1)
plt.plot(x,y2)
plt.xlabel('X', fontsize=24)
plt.ylabel('Y', fontsize=24)
plt.legend(['Quadratic', 'Cubic'], loc=0)
plt.show()<jupyter_output><empty_output><jupyter_text>We can call also use numpy fucntions to make our plots. Numpy is a very powerful math library<jupyter_code># linspace will make a list of values from initial to final with however many increments you want
# this example goes from 0-2.5 with 20 increments
x=numpy.linspace(0,1.0,20)
print(x)
exp_func=np.exp(-2*np.pi*x)
print(exp_func)
plt.plot(x,exp_func, color="black")
plt.xlabel('x', fontsize=24)
plt.ylabel("y(x)", fontsize=24)
plt.show()<jupyter_output><empty_output><jupyter_text>All aspects of the plot can be changed. The best way to figure out what you want to do is to go to the Matplotlib gallery and choose an image that looks like what you are trying to do.https://matplotlib.org/gallery/index.html  Example: Scatter plot with histograms<jupyter_code>import numpy as np

#Fixing random state for reproducibility
np.random.seed(19680801)

# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
spacing = 0.005


rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom + height + spacing, width, 0.2]
rect_histy = [left + width + spacing, bottom, 0.2, height]

# start with a rectangular Figure
plt.figure(figsize=(8, 8))

ax_scatter = plt.axes(rect_scatter)
ax_scatter.tick_params(direction='in', top=True, right=True)
ax_histx = plt.axes(rect_histx)
ax_histx.tick_params(direction='in', labelbottom=False)
ax_histy = plt.axes(rect_histy)
ax_histy.tick_params(direction='in', labelleft=False)

# the scatter plot:
ax_scatter.scatter(x, y)

# now determine nice limits by hand:
binwidth = 0.25
lim = np.ceil(np.abs([x, y]).max() / binwidth) * binwidth
ax_scatter.set_xlim((-lim, lim))
ax_scatter.set_ylim((-lim, lim))

bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins)
ax_histy.hist(y, bins=bins, orientation='horizontal')

ax_histx.set_xlim(ax_scatter.get_xlim())
ax_histy.set_ylim(ax_scatter.get_ylim())

plt.show()<jupyter_output><empty_output><jupyter_text>I don't have to be an expert in making that kind of plot. I just have to understand and guess enough to figure out. I also google things I don't knowhttps://www.google.com/search?client=firefox-b-1-d&q=pyplot+histogram+change+colorhttps://stackoverflow.com/questions/42172440/python-matplotlib-histogram-color?rq=1https://matplotlib.org/examples/color/named_colors.htmlThen I can make small changes to have the plot look how I want it to lookNotice below I changed `ax_scatter.scatter(x, y, color="purple")`, `ax_histx.hist(x, bins=bins, color = "skyblue")`, `ax_histy.hist(y, bins=bins, orientation='horizontal', color="salmon")`<jupyter_code>#Fixing random state for reproducibility
np.random.seed(19680801)

# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
spacing = 0.005


rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom + height + spacing, width, 0.2]
rect_histy = [left + width + spacing, bottom, 0.2, height]

# start with a rectangular Figure
plt.figure(figsize=(8, 8))

ax_scatter = plt.axes(rect_scatter)
ax_scatter.tick_params(direction='in', top=True, right=True)
ax_histx = plt.axes(rect_histx)
ax_histx.tick_params(direction='in', labelbottom=False)
ax_histy = plt.axes(rect_histy)
ax_histy.tick_params(direction='in', labelleft=False)

# the scatter plot:
ax_scatter.scatter(x, y, color="purple")

# now determine nice limits by hand:
binwidth = 0.25
lim = np.ceil(np.abs([x, y]).max() / binwidth) * binwidth
ax_scatter.set_xlim((-lim, lim))
ax_scatter.set_ylim((-lim, lim))

bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins, color = "skyblue")
ax_histy.hist(y, bins=bins, orientation='horizontal', color="salmon")

ax_histx.set_xlim(ax_scatter.get_xlim())
ax_histy.set_ylim(ax_scatter.get_ylim())



plt.show()<jupyter_output><empty_output><jupyter_text>Notice how I changed the colors on the plot based off of what I found on the stack exchange. The way to solve issues in the course and computational work is to google them.  Plotting Exersice 1 Find a plot from the gallery that you like. Then make some sort of noticable change to it.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D


points = np.ones(5)  # Draw 5 points for each line
marker_style = dict(color='tab:blue', linestyle=':', marker='o',
                    markersize=15, markerfacecoloralt='tab:red')

fig, ax = plt.subplots()

# Plot all fill styles.
for y, fill_style in enumerate(Line2D.fillStyles):
    ax.text(-0.5, y, repr(fill_style),
            horizontalalignment='center', verticalalignment='center')
    ax.plot(y * points, fillstyle=fill_style, **marker_style)

ax.set_axis_off()
ax.set_title('fill style')

plt.show()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D


points = np.ones(5)  # Draw 5 points for each line
marker_style = dict(color='tab:green', linestyle=':', marker='o',
                    markersize=15, markerfacecoloralt='tab:purple')

fig, ax = plt.subplots()

# Plot all fill styles.
for y, fill_style in enumerate(Line2D.fillStyles):
    ax.text(-0.5, y, repr(fill_style),
            horizontalalignment='center', verticalalignment='center')
    ax.plot(y * points, fillstyle=fill_style, **marker_style)

ax.set_axis_off()
ax.set_title('fill style')

plt.show()<jupyter_output><empty_output><jupyter_text>Plotting Exersice 2 Plot a the following functions on the same plot from $ -2\pi $ to $2\pi$$$ \sin(2\pi x+\pi)$$$$ \cos(2\pi x+\pi)$$$$\sin(2\pi x+\pi)+\cos(2\pi x+\pi)$$ This might be useful:https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.htmlhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.htmlnumpy.cos<jupyter_code>np.sin(np.pi/2.)

np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )

import matplotlib.pylab as plt
x = np.linspace(-np.pi, np.pi, 201)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.plot(x, np.sin(2*np.pi*x+np.pi))
plt.plot(x, np.cos(2*np.pi*x+np.pi))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.plot(x, np.cos(2*np.pi*x+np.pi))
plt.xlabel('Angle [rad]')
plt.ylabel('cos(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.plot(x, np.sin(2*np.pi*x+np.pi), color="blue")
plt.plot(x, np.cos(2*np.pi*x+np.pi), color="red")
plt.plot(x, np.sin(2*np.pi*x+np.pi)+np.cos(2*np.pi*x+np.pi), color="green")

plt.xlabel('x')
plt.ylabel('y(x)')
plt.axis('tight')

plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.plot(x, np.sin(2*np.pi*x+np.pi), color="black")
plt.plot(x, np.cos(2*np.pi*x+np.pi), color="red")
plt.plot(x, np.sin(2*np.pi*x+np.pi)+np.cos(2*np.pi*x+np.pi), color="gray")

plt.xlabel('x')
plt.ylabel('y(x)')
plt.axis('tight')

plt.show()<jupyter_output><empty_output><jupyter_text>Lecture plots Periodically during lecture we will take a pause to plot some of the interesting functions that we use in class.  Classical wavefunctionsThe following plot shows the the spacial component of the standard wavefunction with a wavelength of $\lambda=\text{1.45 m}$ and a relative amplitude of $A=1$ when the time, $t=0$ and the phase $\phi=1.0$.<jupyter_code>x=np.linspace(0,3.0,100)
sinx=np.sin(2*np.pi*x+0+1)
plt.plot(x,sinx, color="black")
plt.xlabel('x', fontsize=24)
plt.ylabel("y(x)", fontsize=24)
plt.show()<jupyter_output><empty_output><jupyter_text>Make a new figure where you plot the same wave function at three time points in the future. Assume the frequency is $\nu=.1 \text{ ms / s} $ Use a different color for each plot  Orthogonality Graphically show that the the following two functions are orthogonal on the interval $-3\pi$ to $3\pi$$$ \sin(x) \text{ and } \cos(3x)$$Plot both functions together, then plot the product of both functions and explain why it is orthogonal<jupyter_code>import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(3*x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
prod=np.sin(x)*np.cos(3*x)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(3*x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
prod=np.sin(x)*np.cos(3*x)
plt.plot(x, prod, color="blue")
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
prod=np.sin(x)*np.cos(3*x)



prod=np.sin(x)*np.cos(3*x)
x = np.linspace(-3*np.pi, 3*np.pi, 201)
exp_func=prod
np.trapz(exp_func,x)<jupyter_output><empty_output><jupyter_text>Use the numpy trapezoid rule integrator to show the the two functions are orthogonal`np.trapz(y,x)`https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html<jupyter_code># Example code
x=numpy.linspace(0,1.0,20)
exp_func=np.exp(-2*np.pi*x)
np.trapz(exp_func,x)
# Your code here<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1482539966062338, 'fraction_numerical': 0.02259533803697419, 'mean_word_length': 5.330130016958734, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 45, 'https://': 7, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '2861', 'license': 'MIT', 'n_tokens_mistral': 4493, 'n_tokens_neox': 4228, 'n_words': 1116, 'path': '9-19-2019 - Lecture Notebook.ipynb', 'repo_name': 'sju-chem264-2019/9-19-2019-lecture-deannapatti', 'size': '11197'}