For this lesson, we are going to use a few different modules including matplotlib and matplotlib.pyplot. We are going to call matplotlib.pyplot plt.
import math
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
Just like R, we can set values as objects to use them later. In Python, we use an equal sign instead of an assigment operator <-. Run the next code chunks to see how we can use operators in Python.
num = math.fabs(4)
num
## 4.0
four = 4
four
## 4
four + 3
## 7
In the code chunk below, we create an object called rand that consists of 100 random numbers from a normal distribution with mean 0 and standard deviation 1. Then we use the hist function from the matplotlib.pyplot module in Python to plot a histogram of rand. Note that we have to use the show function for the histogram to show up.
rand = np.random.normal(0, 1, 100)
plt.hist(rand)
## (array([ 3., 3., 15., 11., 15., 21., 17., 11., 3., 1.]), array([-2.45769378, -1.95564193, -1.45359007, -0.95153822, -0.44948636,
## 0.0525655 , 0.55461735, 1.05666921, 1.55872107, 2.06077292,
## 2.56282478]), <BarContainer object of 10 artists>)
plt.show()
Write a code chunk to find the factorial of 5 and pass that into an object called fact.
fact = math.factorial(5)
fact
## 120
Write a code chunk to set 3 to an object called num. Then add 7 to num.
num = 3
num + 7
## 10
Write a code chunk to find the square root of 6 and pass that into an object called count. Then divide count by 3.
count = math.sqrt(6)
count / 3
## 0.8164965809277259
Write a code chunk to find 50 random numbers from a normal distribution with mean 0 and standard deviation 1. Set these 50 random numbers to an object called ran. Then plot a histogram of ran.
ran = np.random.normal(0, 1, 50)
plt.hist(ran)
## (array([ 1., 0., 6., 9., 8., 7., 14., 3., 0., 2.]), array([-3.042342 , -2.41491959, -1.78749719, -1.16007478, -0.53265238,
## 0.09477002, 0.72219243, 1.34961483, 1.97703723, 2.60445964,
## 3.23188204]), <BarContainer object of 10 artists>)
plt.show()
1.) Write a code chunk to find set 6 to an object called six. Then subtract 5 from six.
2.) Write a code chunk to find the absolute value of 7 and pass that into an object called fabs.
3.) Write a code chunk to find 3 factorial and pass that into an object called three. Then multiply three by 5.
4.) Write a code chunk to find 200 random numbers from a normal distribution with mean 0 and standard deviation 1. Set these 200 random numbers to an object called hund. Then plot a histogram of hund.