Q06.01 Create a plot of the function $y=\cos(x)$ from $x = -2\pi$ to $2\pi$
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(-2*np.pi,2*np.pi,0.1)
y = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.02 Create a plot of the function $y=\frac{1}{2}{e^x}$ from $x = 0$ to $5$
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(0,5,0.1)
y = 0.5*np.exp(x)
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.03 Create a plot of the function $y=\sqrt{2x}$ from $x = 1$ to $10$
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(0,10,0.1)
y = np.sqrt(2*x)
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.04 Create a plot of the function $y=mx+b$, where $m=-1$ and $b=-4$. Limit the plot to values of $x=-5$ to $5$.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(-5,5,0.1)
m = -1
b = -4
y = m*x+b
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.05 Create a plot of the function $y=ax^2+bx+c$, where $a=1/2$, $b=-1/3$ and $c=4$. Limit the plot to values of $x=-10$ to $10$.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(-10,10,0.1)
a = 1/2
b = -1/3
c = 4
y = a*x**2 + b*x + c
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.06 Create a plot of the function $y=x^3+3$ from $x=-3$ to $3$.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(-3,3,0.1)
y = x**3 + 3
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.07 Create a plot of the function $y=2x^3-9x^2+7x+6$ from $x=-3$ to $4$.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(-3,4,0.1)
y = 2*x**3 -9*x**2 + 7*x + 6
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.08 Plot the data set below with a line plot. Use Matplotlib's default index system, or create a set of x values from $x=0$ to $4$.
$$ y = [-1,\ 2,\ -3,\ 1,\ 0] $$import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
y = [-1, 2, -3, 1, 0]
fig, ax = plt.subplots()
ax.plot(y)
plt.show()
Q06.09 Plot the following three functions on the same set of axis. Use a different color line for each function.
$$ x = \cos(t) $$$$ y = \cos(t/2) $$$$ z = \frac{1}{2}\cos(t) $$Set values of $t=-4\pi$ to $4\pi$
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
t = np.arange(-4*np.pi,4*np.pi,0.1)
x = np.cos(t)
y = np.cos(t/2)
z = 0.5*np.cos(t)
fig, ax = plt.subplots()
ax.plot(t,x, 'r')
ax.plot(t,y, 'g')
ax.plot(t,z, 'b')
plt.show()
Q06.10 Plot the following three functions on the same set of axis. Specify a thick red line for the $cos$ function, a thin blue line for the $sin$ function, and a dashed green line for the $atan$ function (the arc tangent function).
$$ x = cos(r/10) $$$$ y = sin(r/4) $$$$ z = atan(r) $$Set values of $r=-1/2$ to $1/2$
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
r = np.arange(-0.5,0.5,0.01)
x = np.cos(r/10)
y = np.sin(r/4)
z = np.arctan(r)
fig, ax = plt.subplots()
ax.plot(r,x, 'r', linewidth=5.0)
ax.plot(r,y, 'b', linewidth=0.5)
ax.plot(r,z, 'g', linewidth=0.5)
plt.show()
Q06.30 According to the University of Waterloo, world energy consumption in 2006 from the five top energy resources were:
$$ Natural \ Gas = 24\% $$$$ Hydro = 6\% $$$$ Nuclear = 6\% $$$$ Oil = 36\% $$$$ Coal = 28\% $$Build a pie chart of the distribution of world energy consumption based on the data above.
import matplotlib.pyplot as plt
sizes = [24, 6, 6, 36, 28]
labels = ['Natural Gas','Hydro','Nuclear','Oil','Coal']
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.0f%%')
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('World Energy Consumption')
plt.show()
Q06.31 According to the 2017 Python Developer's Survey, the computer operating system used by Python Developers breaks down as follows:
$$ Windows = 49\% $$$$ Linux = 19\% $$$$ MacOS = 15\% $$$$ Other = 17\% $$Build a pie chart of the computer operating system used by Python Developers in 2017.
import matplotlib.pyplot as plt
sizes = [49, 19, 15, 17]
labels = ['Windows','Linux','MacOS','Other']
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.0f%%')
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('Operating system used by Python developers')
plt.show()
Q06.32 According to the 2017 Python Developer's Survey, the commercial cloud providers used by Python Developers breaks down as follows:
$$ Amazon \ Web \ Services = 67\% $$$$ Google \ Cloud = 29\% $$$$ Heroku = 26\% $$$$ Digital \ Ocean = 23\% $$$$ Microsoft \ Azure = 16\% $$$$ Other = 13\% $$Build a pie chart of the commercial cloud providers used by Python Developers in 2017.
import matplotlib.pyplot as plt
sizes = [67, 29, 26, 23, 16, 13]
labels = ['AWS','Google Cloud','Heroku','Digital Ocean','Azure','Other']
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.0f%%')
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('Commercial Cloud Providers\nused by Python Developers')
plt.show()
Q06.33 Re-create the pie chart in Q06.32 that shows which commercial cloud providers are used by Python Developers. Explode out the pie pieces on the chart and add a shadow to each piece.
import matplotlib.pyplot as plt
sizes = [67, 29, 26, 23, 16, 13]
labels = ['AWS','Google Cloud','Heroku','Digital Ocean','Azure','Other']
explode = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1)
fig, ax = plt.subplots()
ax.pie(sizes,
explode=explode,
labels=labels,
autopct='%1.0f%%',
shadow=True,
startangle=90)
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('Operating system used by Python developers')
plt.show()
Q06.34 Re-create the pie chart in Q06.31 that shows which operating system Python developers use. Explode out the Windows (49%) pie piece to highlight it.
import matplotlib.pyplot as plt
sizes = [49, 19, 15, 17]
labels = ['Windows','Linux','MacOS','Other']
explode = (0.4, 0, 0, 0)
fig, ax = plt.subplots()
ax.pie(sizes,
explode=explode,
labels=labels,
autopct='%1.0f%%',
shadow=True,
startangle=90)
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('Operating system used by Python developers')
plt.show()
Q06.35 A list of grades in a college engineering course and the corresponding number of students who earned each grade is shown below:
grades = ['A','B','C','D','F']
number_of_students = [3, 5, 8, 1, 2]
Build a bar plot of the grade distribution from the college engineering class.
import matplotlib.pyplot as plt
grades = ['A','B','C','D','F']
number_of_students = [3, 5, 8, 1, 2]
x_pos = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.bar(x_pos, number_of_students, align='center', alpha=0.5)
ax.set_xlabel('Grade')
ax.set_ylabel('Number of Students')
ax.set_xticks(x_pos)
ax.set_xticklabels(grades)
ax.set_title('Grades in a College Engineering Course')
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
Q06.36 The proof strength of four different grades of bolts is shown below:
Bolt Type | Proof Strength (psi) |
---|---|
Grade 2 | 33,000 psi |
Grade 5 | 74,000 psi |
Grade 8 | 120,000 psi |
Grade A325 | 85,000 psi |
Build a bar chart of the proof strength of the four types of bolts. Label the bars by bolt type and include a title and y-axis label with units.
import matplotlib.pyplot as plt
bolt_types = ['Grade 2','Grade 5','Grade 8','Grade A325']
proof_strength = [33000, 74000, 120000, 85000]
x_pos = [0,1,2,3]
fig, ax = plt.subplots()
ax.bar(x_pos, proof_strength, align='center', alpha=0.5)
ax.set_ylabel('Proof Strength (psi)')
ax.set_xlabel('Bolt Type')
ax.set_xticks(x_pos)
ax.set_xticklabels(bolt_types)
ax.set_title('Proof Strength of Four Bolt Types')
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
Q06.37 According to the 2017 Python Developer's Survey, the IDE (Integrated Development Environment) used by Scientific Python Developers breaks down as follows:
$$ PyCharm \ Professional = 12\% $$$$ PyCharm \ CE = 17\% $$$$ Sublime \ Text = 9\% $$$$ Vim = 8\% $$$$ IDLE = 7\% $$$$ Atom = 7\% $$$$ VS \ Code = 6\% $$$$ Notepad \ ++ = 6\% $$$$ Eclipse = 3\% $$$$ Emacs = 3\% $$Build a bar chart of the IDE's used by Python Developers in 2017.
import matplotlib.pyplot as plt
import numpy as np
ides = ['PyCharm\nProfessional','PyCharm CE','Sublime Text','Vim','IDLE','Atom','VS Code','Notepad ++','Eclipse','Emacs']
useage = [12, 17, 9, 8, 7, 7, 6, 6, 3, 3]
x_pos = np.arange(len(useage))
fig, ax = plt.subplots(figsize=(12,5))
ax.bar(x_pos, useage, align='center', alpha=0.5)
ax.set_ylabel('Usage Rate (%)')
ax.set_xlabel('Python IDE')
ax.set_xticks(x_pos)
ax.set_xticklabels(ides)
ax.set_title("Python IDE's Used by Scientific Python Developers")
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
Q06.38 Create a plot of the function $y=x^3+3$ from $x=-3$ to $x=3$.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3,3,0.1)
y = x**3 + 3
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
Q06.39 The tensile strength of 4 steel heat treatments is shown in the table below:
Heat Treatment | Tensile Strength (MPa) |
---|---|
Annealed | 390 MPa |
Normalized | 452 MPa |
Oil Quench | 734 MPa |
Oil Quench and Temper | 422 MPa |
Build a bar plot of tensile strength vs. heat treatment using the steel heat treatment data above. Label the bars with the type of heat treatment and include a y-axis label with units and a title.
import matplotlib.pyplot as plt
heat_treatments = ['Annealed','Normalized','Oil Quench','Oil Quench and Temper']
strength = [390, 452, 734, 422]
x_pos = [0,1,2,3]
fig, ax = plt.subplots()
ax.bar(x_pos, strength, align='center', alpha=0.5)
ax.set_ylabel('Tensile Strength (MPa)')
ax.set_xlabel('Heat Treatment')
ax.set_xticks(x_pos)
ax.set_xticklabels(heat_treatments)
ax.set_title('Tensile Strength vs. Heat Treatment')
ax.yaxis.grid(True)
plt.tight_layout()
plt.show()
Q06.50 Plot the histogram of a normal distribution of 100
random numbers. Use NumPy's np.random.normal()
function to create the array of numbers. Set a mean $\mu$ = 20
and a standard deviation $\sigma$ = 7
.
import numpy as np
import matplotlib.pyplot as plt
mu = 20
sigma = 7
x = np.random.normal(mu, sigma, size=100)
fig, ax = plt.subplots()
ax.hist(x, 20)
ax.set_title('Historgram of 100 Normally Distributed Random Numbers')
ax.set_xlabel('Bin Range')
ax.set_ylabel('Frequency')
fig.tight_layout()
plt.show()
Q06.51 NumPy's np.random.randint()
function creates an array of random numbers. NumPy's np.random.randn()
function creates an array of normally-distributed random numbers. Use both of these functions to create a set of 200 random numbers. Plot both sets of numbers as histograms with Matplotlib's ax.hist()
method. After you construct both histograms, explain how the two NumPy functions np.random.randint()
and np.random.randn()
compare.
import numpy as np
import matplotlib.pyplot as plt
mu = 20
sigma = 7
x1 = np.random.normal(mu, sigma, size=200)
x2 = np.random.randint(30, size=200)
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2, figsize=(9,3))
ax1.hist(x1, 20)
ax1.set_title('Normally Distributed Random Numbers')
ax1.set_xlabel('Bin Range')
ax1.set_ylabel('Frequency')
ax2.hist(x2, 100)
ax2.set_title('Random Integers')
ax2.set_xlabel('Bin Range')
ax2.set_ylabel('Frequency')
fig.tight_layout()
plt.show()
NumPys np.random.normal()
function creates a set of numbers with a normal distribution. The resulting histogram looks sort of like a bell curve. NumPy's np.random.randint()
function creates random integers in a given range. The histogram that results looks "flat".
Q06.52 Create a box plot with three elements (three "boxes"). Use NumPy's np.random.randn()
function to create three arrays of 50 elements. Plot each array as a separate element on the box plot.
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(50)
x2 = np.random.randn(50)
x3 = np.random.randn(50)
data = list([x1, x2, x3])
fig, ax = plt.subplots()
ax.boxplot(data)
ax.set_title('box plot')
xticklabels = ['data set 1', 'data set 2', 'data set 3']
ax.set_xticklabels(xticklabels)
ax.yaxis.grid(True)
plt.show()
Q06.53 Create a violin plot with five elements (five "violins"). Use NumPy's np.random.randn()
function to create five arrays of 50 elements. Plot each array as a separate element on the violin plot.
import numpy as np
import matplotlib.pyplot as plt
# if using a Jupyter notebook, include:
%matplotlib inline
# generate some random data
x1 = np.random.randn(50)
x2 = np.random.randn(50)
x3 = np.random.randn(50)
x4 = np.random.randn(50)
x5 = np.random.randn(50)
data = list([x1, x2, x3, x4, x5])
fig, ax = plt.subplots()
ax.violinplot(data, showmeans=True, showmedians=False)
ax.set_title('violin plot')
xticklabels = ['x1', 'x2', 'x3', 'x4', 'x5']
ax.set_xticks([1,2,3,4,5])
ax.set_xticklabels(xticklabels)
ax.yaxis.grid(True)
plt.show()
Q06.54 Use Matplotlib's plt.subplots()
command to create a figure with three subplots. In the first subplot, build a historgram. In the second subplot build a box plot. In the third subplot build a violin plot. Plot the same set of 100 normally-distributed random numbers (using NumPy's np.random.randn()
function) in each subplot. Include a title above each subplot that shows the plot type: Histogram, Box Plot, and Violin Plot.
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1,ax2,ax3) = plt.subplots(nrows=1,ncols=3,figsize=(12,3))
x = np.random.randn(100)
ax1.hist(x, 20)
ax1.set_title('Historgram')
ax2.boxplot(x)
ax2.set_title('Box Plot')
ax3.violinplot(x, showmeans=True, showmedians=False)
ax3.set_title('Violin Plot')
fig.tight_layout()
plt.show()
Q06.60 Create a scatter plot with the following lists of x points and y points.
x = [1,2,3,4,5]
y = [8,12,4,2,6]
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [8,12,4,2,6]
fig, ax = plt.subplots()
ax.scatter(x, y)
plt.show()
Q06.61 Create a scatter plot with the following arrays of x points and y points generated with NumPy's np.random.randint()
function.
x = np.random.randint(0,15,size=20)
y = np.random.randint(0,10,size=20)
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(0,15,size=20)
y = np.random.randint(0,10,size=20)
fig, ax = plt.subplots()
ax.scatter(x, y)
plt.show()
Q06.62 Use the code below to create two arrays of semi-focused random points.
x1 = 1.5 * np.random.randn(150) + 10
y1 = 1.5 * np.random.randn(150) + 10
x2 = 1.5 * np.random.randn(150) + 4
y2 = 1.5 * np.random.randn(150) + 4
x = np.append(x1,x2)
y = np.append(y1,y2)
Plot the arrays x
and y
on a scatter plot. Set the color of the marker's on the scatter plot red. Set the marker opacity to 0.5
.
import matplotlib.pyplot as plt
import numpy as np
x1 = 1.5 * np.random.randn(150) + 10
y1 = 1.5 * np.random.randn(150) + 10
x2 = 1.5 * np.random.randn(150) + 4
y2 = 1.5 * np.random.randn(150) + 4
x = np.append(x1,x2)
y = np.append(y1,y2)
fig, ax = plt.subplots()
ax.scatter(x, y, color='red', alpha=0.5)
plt.show()
Q06.70 Create a figure that has four subplots all in one row. In each of the subplots plot the function:
$$ y = e^x $$Use the same values of x and y in each subplot. Set the values of x with NumPy's arange()
function with the line x = np.arange(0.01, 20.0, 0.01)
In the first subplot, use Matplotlibs's ax.plot()
method. In the second subplot use Matplotlib's ax.semilogy()
method. In the thrid subplot use Matplotlib's ax.semilogx()
method. In the four subplot use Matplotlib's ax.loglog()
method. Label each subplot with a title that shows the plot type.
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows=1,ncols=4,figsize=(12,3))
x = np.arange(0.01, 20.0, 0.01)
y = np.exp(x)
ax1.plot(x, y)
ax1.set_title('linear x, linear y')
ax2.semilogy(x,y)
ax2.set_title('linear x, log y')
ax3.semilogx(x,y)
ax3.set_title('log x, linear y')
ax4.loglog(x,y)
ax4.set_title('log x, log y')
fig.tight_layout()
plt.show()
Q06.71 Use the data in Q06.31 to create a figure with two subplots. In the first subplot, build a bar chart of the data in Q06.31. In the second subplot, build a pie chart of the data in Q06.31.
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize=(12,5))
sizes = [49, 19, 15, 17]
labels = ['Windows','Linux','MacOS','Other']
x_pos = [0,1,2,3]
ax1.bar(x_pos, sizes, align='center', alpha=0.5)
ax1.set_title('Bar Chart of\nOperating system used by Python developers')
ax1.set_ylabel('Percentage Use (%)')
ax1.set_xlabel('Operating Sysem')
ax1.set_xticks(x_pos)
ax1.set_xticklabels(labels)
ax1.set_title('Bar Chart of\nOperating system used by Python developers')
ax1.yaxis.grid(True)
ax2.pie(sizes, labels=labels, autopct='%1.0f%%')
ax2.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax2.set_title('Pie Chart of\nOperating system used by Python developers')
fig.tight_layout()
plt.show()