Exercise 1. Using Functional approach for line plot

In [208]:
import numpy as np

'''1. Generating an array of numbers for the horizontal axis ranging from 0 to 10 in 20 evenly spaced values'''

x = np.linspace(0,10,20)

'''2. Create an array and save it as object y. 
The snippet of the following code cubes the values of x and saves it to the array, y'''

y = x**3

'''3. creating the plot'''

import matplotlib.pyplot as plt
plt.plot(x,y)
plt.title("Look at figure 1")
plt.show()


'''4. Adding the x-label'''

plt.xlabel("Linearly spaced numbers")

'''5. Adding a y-label'''

plt.ylabel("y-value")

'''6. Adding a title'''

plt.title("x by x cubed--Look at figure 2")

'''7. changing the line color to black by specifying the color argument as k in plt.plot() function:'''

plt.plot(x,y,'k')
plt.show()

'''8.Changing the line curve to diamond using character D, combined with color character k'''

plt.plot(x,y,'Dk')
plt.title("Look at figure 3")
plt.show()

'''9. Connecting the diamonds with solid line placing '-' between 'D' and 'k'''

plt.plot(x,y,'D-k')
plt.title("Look at figure 4")
plt.show()

'''10. Increasing the font size of the title'''

plt.title("x by x cubed--look at figure 5",fontsize = 20)
plt.plot(x,y,"D-k")
plt.show()

Exercise 2. Functional Approach to add a 2nd line to the above plot

In [39]:
'''1.Using the previous plot'''

x = np.linspace(0,10,20)
y = x**3

''' 2. Renaming the title using '\n' character'''


plt.title("As x increases,\nx Cubed(black diamond line) increases \nat a Greater rate than \nx squared (red dotted line)",
           fontsize =22)
plt.xlabel("Linearly spaced numbers")
plt.ylabel("y-value")

'''3.adding legend to the plot using label inside the plt.plot().'''

plt.plot(x,y,"D-k",label = 'x-cubed')

'''4.Create another y object as we did above and instead of cubing x, do x squared'''

y2 = x**2

'''5. lot using dotted red color'''

plt.plot(x,y2,'--r',label = 'x-squared')

'''6. specify the location of the legend'''

plt.legend(loc = 'upper left')
plt.show()

7. Now let's change the dimension of the plot

In [40]:
'''To change the dimensions of our plot, we will need to add plt.figure(figsize=(10,5)) to the top of our plt instances. 
The figsize arguments of 10 and 5 specify the width and height'''

plt.figure(figsize=(10,5))

x = np.linspace(0,10,20)

y = x**3

plt.title("As x increases,\nx Cubed(black diamond line) increases \nat a Greater rate than \nx squared (red dotted line)",
           fontsize =22)
plt.xlabel("Linearly spaced numbers")
plt.ylabel("y-value")
plt.plot(x,y,"D-k",label = 'x-cubed')
y2 = x**2
plt.plot(x,y2,'--r',label = 'x-squared')
plt.legend(loc = 'upper left')
plt.show()

Activity -1 : Line Plot

Let's create a line plot to analyze the month-to-month trends for items sold in the months January through June.

The trend will be positive and linear, and will be represented using a dotted, blue line, with star markers.

The x-axis will be labeled 'Month' and the y-axis will be labeled 'Items Sold'. The title will say 'Items Sold has been Increasing Linearly:'

In [49]:
x = ['Jan','Feb','Mar','Apr','May','Jun']
y = [1000,1200,1400,1600,1800,2000]
plt.xlabel("Month")
plt.ylabel("Items Sold")
plt.plot(x,y,"--*")
plt.show()

Exercise 3: Creating a Bar Plot

In this exercise we will create bar plot for different items grouped by their sales revenue

In [63]:
''' 1. Create a list of Items and save it as x'''

x = ['Shirts','Pants','Shorts','Shoes']

'''2. Create a list of sales revenue and save it as y'''

y = [5000,1200,800,1800]

'''3. Add title to the plot'''

plt.title("Sales revenue by Item type")

'''4. Creating the x and y label'''

plt.xlabel("Item type")
plt.ylabel("Sales revenue($)")

'''5. Fetching the max value index for y and its corresponding x'''

index_of_max_y = y.index(max(y))
print("index_of_max_y: ",index_of_max_y)

most_sold_item = x[index_of_max_y]
print("most_sold_item: ",most_sold_item)

'''6. Now programatically displaying the title based on the max revenue generated by item'''

plt.title('{} produce the most sales revenue'.format(most_sold_item))

'''7. Create a bar plot'''

plt.bar(x,y)
plt.show()
index_of_max_y:  0
most_sold_item:  Shirts

8. Now lets switch the bar plot to horizontal.

In [65]:
''' 1. Create a list of Items and save it as x'''

x = ['Shirts','Pants','Shorts','Shoes']

'''2. Create a list of sales revenue and save it as y'''

y = [5000,1200,800,1800]

'''3. Add title to the plot'''

plt.title("Sales revenue by Item type")

'''4. Creating the x and y label'''

plt.xlabel("Item type")
plt.ylabel("Sales revenue($)")

'''5. Fetching the max value index for y and its corresponding x'''

index_of_max_y = y.index(max(y))
print("index_of_max_y: ",index_of_max_y)

most_sold_item = x[index_of_max_y]
print("most_sold_item: ",most_sold_item)

'''6. Now programatically displaying the title based on the max revenue generated by item'''

plt.title('{} produce the most sales revenue'.format(most_sold_item))

'''7. Create a horizontal bar plot'''

plt.barh(x,y)
plt.show()
index_of_max_y:  0
most_sold_item:  Shirts

Now if you notice above, there is a mistake in the above plot. Basically when we switch the bar plot from vertical to horizontal, the x and y axes needs to be switched as well.

In [69]:
''' 1. Create a list of Items and save it as x'''

x = ['Shirts','Pants','Shorts','Shoes']

'''2. Create a list of sales revenue and save it as y'''

y = [5000,1200,800,1800]

'''3. Add title to the plot'''

plt.title("Sales revenue by Item type")

'''4. Creating the x and y label'''

plt.xlabel("Sales revenue($)")
plt.ylabel("Item type")

'''5. Fetching the max value index for y and its corresponding x'''

index_of_max_y = y.index(max(y))
print("index_of_max_y: ",index_of_max_y)

most_sold_item = x[index_of_max_y]
print("most_sold_item: ",most_sold_item)

'''6. Now programatically displaying the title based on the max revenue generated by item'''

plt.title('{} produce the most sales revenue'.format(most_sold_item))

'''7. Create a horizontal bar plot'''
plt.barh(x,y)
plt.show()
index_of_max_y:  0
most_sold_item:  Shirts

Activity 2: Bar Plot

In this activity, we will be creating a bar plot comparing the number of NBA championships among the five franchises with the most titles. The plot will be sorted so that the franchise with the greatest number of titles is on the left and the franchise with the least is on the right. The bars will be red, the x-axis will be titled 'NBA Franchises', the y-axis will be titled 'Number of Championships', and the title will be programmatic, explaining which franchise has the most titles and how many they have.

Additionally, we will rotate the x-tick labels 45 degrees using plt.xticks(rotation=45) so that they do not overlap, and we will save our plot to the current directory:

In [74]:
'''1. Creating a list of 5 teams with the most NBA titles and assigning it to variable x'''

x = ['Boston Celtics','Los Angeles Lakers','Chicago Bulls','Golden State Warriors','San Antonio Spurs']

'''2. Creating a list of 5 values for y for "Titles Won" corresponding to the strings x'''

y = [17,16,6,6,5]


'''3.Create a data frame and place the values of x and y with column names "Team" and "Titles"'''

import pandas as pd

df = pd.DataFrame({"Team":x,
                  "Titles":y})

'''4. Sort the dataframe in descending order by Titles and save it to df_sorted'''

df_sorted = df.sort_values(by="Titles",ascending=False)

'''5.Make a programmatic title and save it as title by first finding the team with the most titles 
and saving it as the "team_with_most_titles" object'''

team_with_most_titles = df_sorted['Team'][0]

'''6.retrieve the number of titles for the team with the most titles'''

most_titles = df_sorted['Titles'][0]

'''7.Create the title based on the most no of titles won by the team'''

title = 'The {} have the most titles with {}'.format(team_with_most_titles,most_titles)

'''8. Plot the number of titles by team below'''

plt.bar(df_sorted['Team'],df_sorted['Titles'],color = 'red')

'''9. Set the x and y label'''

plt.xlabel('Team')
plt.ylabel('No of Chanpionships')

'''10. To prevent the x tick labels from overlapping by rotating them 45 degrees'''

plt.xticks(rotation=45)

plt.title(title)

plt.savefig("Titles_by_Team")




'''Note: When we print the plot to the console using plt.show(), it appears as intended; 
however, when we open the file we created titled 'Titles_by_Team.png', we see that it crops the x tick labels
(check the cell below).The figure will display the bar plot with the cropped x tick labels.'''

'''11. To fix the cropping issue, add bbox_inches='tight' as an agrument inside plt.savefig()'''

plt.savefig("Titles_by_Team_updated",bbox_inches='tight')
plt.show()
  1. Image where the X labels are cropped

title

  1. Image where the complete X labels are shows after using the bbox_inches='tight' argument

title

Exercise 4: Now let's create Histogram using functional approach

It is important to be aware of the distribution of continuous variable in statistics before running any kind of analysis. Let's use histogram to see how the continuous distribution can be plotted. Histograms display the frequency by bin for a given array.

1.To demonstrate the creation of a histogram, we will generate an array of 100 normally distributed values with a mean of 0 and a standard deviation of 0.1

In [90]:
import numpy as np
In [91]:
x = np.random.normal(loc= 0, scale=0.1, size =100)

2. Create a histogram with no of bins = 20

In [92]:
plt.hist(x,bins=20)
plt.xlabel('x-value')
plt.ylabel('frequency')
plt.show()

Test for Normality of a distribution

Looking at a Histogram we can determine wherher a distribution is normal or not. However sometimes it is difficult to determine this. A distribution may appear normal when it is not, and sometimes a distribution may appear not normal when it is normal.

To test the Normality of the distribution we will use the Shapiro-Wilk test.

1. The null hypothesis for the Shapiro-Wilk test is that data is normally distributed.

Thus, a p-value < 0.05 indicates a non-normal distribution while a p-value > 0.05 indicates a normal distribution.

In this use case we will be using the Shapiro-wilk test to create a programmatic title which will tell the reader whether the distribution is normal or not.

3. Using the tuple unpacking to save the W statistic and P-value from Shapiro-wilk test into the variables shap_w and shap_p

In [93]:
from scipy.stats import shapiro

shap_w, shap_p = shapiro(x)
In [94]:
print("The value of shap_w is {} and shap_p is {}".format(shap_w,shap_p))
The value of shap_w is 0.9630911946296692 and shap_p is 0.006720527540892363

4.Using conditional statement to determine whether data is distributed normally

In [95]:
if shap_p>0.05:
    normal_YN = 'Failed to reject the null hypothesis. Hence the data is normally distributed'
else:
    normal_YN = 'Rejecting Null hypothesis as the Data is normally distributed'

5. Based on the conditional outcome, assiging the value of normal_YN to the title of the plot.

In [97]:
plt.title(normal_YN)
plt.hist(x)
plt.show()
So from the above plot we understood that histograms are mostly used for displaying the distributions of an array. Another very useful plot is the box-whisker plot. These plots display the distributions of an array based on the minimum, first quartile, median, third quartile, and maximum, but they are primarily used to indicate the skew of a distribution and to identify outliers.

Exercise 5: Box and Whisker Plot -- Functional Approach

1. Let's generate an array of 100 normally distributed numbers with a mean of 0 and standard deviation of 0.1

In [99]:
x = np.random.normal(loc = 0, scale = 0.1, size= 100)

2. Create the plot as below

In [100]:
import matplotlib.pyplot as plt

plt.boxplot(x)
plt.show()

i. The plot displays a box that represents the interquartile range (IQR).

ii. The top of the box is the 25th percentile (i.e., Q1) while the bottom of the box is the 75th percentile (that is, Q3).

iii. The orange line going through the box is the median.

iv. The two lines extending above and below the box are the whiskers. The top of the upper whisker is the "maximum" value, which is calculated using Q1 – 1.5*IQR.

v. The bottom of the lower whisker is the "minimum" value, which is calculated using Q3 + 1.5*IQR.

vi. Outliers are displayed as dots above the "maximum" whisker or below the "minimum" whisker.

In [101]:
shap_w, shap_p = shapiro(x)
In [102]:
print("The value of shap_w is {} and the value of shap_p is {}".format(shap_w,shap_p))
The value of shap_w is 0.9899097084999084 and the value of shap_p is 0.6572926640510559

3. Converting the x values into z-score.

z-score describes the position of a raw score in terms of its distance from the mean, when measured in standard deviation units. The z-score is positive if the value lies above the mean, and negative if it lies below the mean.

In [104]:
from scipy.stats import zscore

XZ_score = zscore(x)
print("The Value of z_scores are {}".format(XZ_score))
The Value of z_score is [ 2.52990430e-01  1.90082257e-01 -5.21117119e-01 -1.54512859e+00
 -3.52050618e-01 -4.95245614e-01 -1.99913793e-01 -9.84426917e-01
  3.73201232e-01  1.12707427e+00 -2.78724110e-01  5.95931611e-01
 -1.16209311e+00  1.20165681e+00 -3.27414015e-01  4.46335244e-01
  6.84477466e-01 -8.31552557e-01  1.24838250e+00 -2.58905197e-01
 -8.34989777e-02 -9.63650703e-01 -1.32117714e-01  6.88115804e-01
  3.84296834e-01 -7.02647585e-01  2.36397969e-01  4.11548473e-01
  1.02509050e+00  1.42197415e+00  1.02926590e+00  1.47891800e+00
 -2.02154657e+00 -3.31376703e-01 -1.82707830e+00 -8.38136841e-01
 -9.84895443e-01 -1.90149102e+00  1.84492129e-01 -1.41376861e+00
 -1.05158945e+00  1.08685961e+00 -2.20127965e+00  2.00723792e-01
 -4.62096990e-01  4.08465616e-01 -8.23852252e-01 -1.31894094e-01
 -3.06571190e-01  3.63985341e-01  1.11863882e+00 -5.98202423e-02
 -2.64014334e-01 -1.27243752e-01 -1.46702303e+00  7.52216344e-01
  3.95661632e-01  5.15145191e-01  2.27832538e-01  2.09735773e+00
 -1.00939044e+00  8.68191829e-01  1.35934184e+00 -3.44697443e-01
  1.06645364e-01  1.65333374e+00 -8.24468889e-01  1.19188836e+00
 -1.99491376e+00 -1.57827250e-04  1.70368753e+00  3.75676055e-01
 -8.08872978e-01  2.84812833e+00  1.02660448e+00  2.25744806e-01
  1.09115818e-01 -4.65349437e-01 -5.78710411e-01  1.20990026e+00
  2.10862778e-01 -1.37615714e+00 -7.76132996e-01 -1.71889101e+00
 -9.10097869e-01  1.16978454e-01 -4.98619504e-01 -4.85865912e-02
 -1.49082213e+00  1.35461127e-01  1.04330445e+00 -1.69526489e+00
  1.37420690e+00  1.33342843e+00 -5.67159033e-01  4.84460598e-01
  5.93692600e-01  1.12281012e+00  1.05215179e+00 -1.32276434e-01]

4. Now let's iterate through the z-scores and see how many outliers are present in the data

In [115]:
total_outliers = 0

for i in range(len(XZ_score)):
    if abs(XZ_score[i])>=2:
        total_outliers+=1
    
print("The total outliers are {}".format(total_outliers))
The total outliers are 4

5. Let's generate a title that communicates whether the data, as well as the number of outliers, is normally distributed. If shap_p is greater than 0.05, our data is normally distributed. If it is not greater than 0.05, then our data is not normally distributed.

In [116]:
if shap_p > 0.05:
    title = 'The data is normally distributed with {} number of outliers'.format(total_outliers)
else:
    title = 'The data is not normally distributed with {} number of outliers'.format(total_outliers)

6. Programatically assigning the title of the plot

In [119]:
plt.title(title)
plt.boxplot(x)
plt.show()

Using histograms and box-whisker plots, we can easily determine the characteristics of the numerical array like the z-score, p-value.

But what if we want to determine the relationship between the arrays. So to do this we need to switch to scatter plot which will show the relationship between 2 continuous arrays.

Exercise 5: ScatterPlot

Let's create a scatter plot of weight vs height and programatically create a title which would explain the relationship between these 2 attributes

1. generating a list of numbers which will represent height

In [120]:
y = [5, 5.5, 5, 5.5, 6, 6.5, 6, 6.5, 7, 5.5, 5.25, 6, 5.25]

2. generating a list of numbers which will represent weight

In [122]:
x = [100, 150, 110, 140, 140, 170, 168, 165, 180, 125, 115, 155, 135]

3. creating the scatter plot with weight on the x-axis and height on the y-axis

In [123]:
plt.scatter(x,y)
plt.show()

From the plot above, the user is not getting an idea about the relationship between 2 continuous arrays. In order to get an idea about the strength of relationship we use Pearson correlation coefficient.

Pearson correlation coefficient is an indicator of the strength and direction of the linear relationship of the 2 continuous arrays.

In [125]:
from scipy.stats import pearsonr

correlation_coeff, p_value = pearsonr(x,y)
In [126]:
print("The value of correlation_coeff is {} and the p_value is {}".format(correlation_coeff,p_value))
The value of correlation_coeff is 0.906224645847121 and the p_value is 1.9704521537621127e-05
In [127]:
if correlation_coeff==1.00:
    title="This is a perfect, positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff>=0.8:
    title="There is a very strong, positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff>=0.6:
    title="There is a strong, positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff>=0.4:
    title="There is a moderate, positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff>=0.2:
    title="There is a weak, positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff>0:
    title="There is a very weak,positive linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff==0:
    title="There is no linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff<=-0.8:
    title="There is a very strong, negative linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff<=-0.6:
    title="There is a strong, negative linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff<=-0.4:
    title="There is a moderate, negative linear relationship (r={0:0.2f})".format(correlation_coeff)
elif correlation_coeff<=-0.2:
    title="There is a weak, negative linear relationship (r={0:0.2f})".format(correlation_coeff)
else:
    title="There is a very weak, negative linear relationship r({0:0.2f})".format(correlation_coeff)
print(title)
    
There is a very strong, positive linear relationship (r=0.91)

4. Now let's use the above logic and set the title of the graph

In [128]:
plt.scatter(x,y)
plt.title(title)
plt.show()

Object oriented approach for using subplots

So we have learned how to create and style plots for several different purposes using the functional approach.

While this approach of plotting is effective for generating quick visualizations, it does not allow us to create multiple subplots or store the plot as an object in our environment.

To save the plot as an object in our environment, we must use the object-oriented approach, which will be covered in the following exercises and activities.

Using the functional approach of plotting in Matplotlib does not allow the user to save the plot as an object in the environment.

However with object-oriented approach, we create a figure object that acts as an empty canvas and then we add a set of axes, or subplots, to it. The figure object is callable and, if called, will return the figure to the console.

Exercise 6: Single line plots using subplots

In [129]:
x = np.linspace(0,10,20)
y = x**3
In [130]:
import matplotlib.pyplot as plt
In [143]:
fig, axes = plt.subplots()
axes.plot(x,y)
axes.plot(x,y,"D-k")
axes.set_xlabel('Linearly Spaced Numbers')
axes.set_ylabel("y-value")
axes.set_title("As X increases, y increases")
print(fig)
plt.show()
Figure(432x288)

In the above exercise we created a plot which was similar to what we created in Exercise 1, however this time its a callable object. Also, using the object oriented approach, we can create multiple subplots on a single figure object.

Let's go ahead and see how we could use the create multiple subplots using a single figure object in the next exercise

Exercise 7:Multiple plots using subplots

In [157]:
import numpy as np
x = np.linspace(0,10,20)
y = x**3
y1 = x**2
print(x)
[ 0.          0.52631579  1.05263158  1.57894737  2.10526316  2.63157895
  3.15789474  3.68421053  4.21052632  4.73684211  5.26315789  5.78947368
  6.31578947  6.84210526  7.36842105  7.89473684  8.42105263  8.94736842
  9.47368421 10.        ]
In [158]:
import matplotlib.pyplot as plt

'''1.Create a figure with two axes (that is, subplots) that are side by side (that is, 1 row with 2 columns)'''
fig, axes = plt.subplots(nrows=1, ncols = 2)

'''2. To access the subplot on the left, refer to it as axes[0]. To access the plot on the right, 
      refer to it as axes[1].'''
axes[0].plot(x,y)

'''3. Title of the 1st subplot'''

axes[0].set_title('x by y cubed')

'''4. X-axis label to 1st subplot'''

axes[0].set_xlabel('Linearly spaced numbers')

'''5. Y-axis label to 1st subplot'''

axes[0].set_ylabel('y-value')

'''6. Plotting the 2nd subplot on the right using y2, x'''

axes[1].plot(x,y1)

'''7. Adding a title to the plot'''

axes[1].set_title('x by y squared')

'''8. X-axis label to 2nd subplot'''

axes[1].set_xlabel('Linearly Spaced numbers')

'''9. Y-axis label to 2nd subplot'''

axes[1].set_ylabel('y-value')
plt.show()
In [161]:
'''However if you look closely, the y-value in the right subplot is overlapping into the left plot.
   To prevent overlapping we use plt.tight.layout()'''

import matplotlib.pyplot as plt

'''1.Create a figure with two axes (that is, subplots) that are side by side (that is, 1 row with 2 columns)'''
fig, axes = plt.subplots(nrows=1, ncols = 2)

'''2. To access the subplot on the left, refer to it as axes[0]. To access the plot on the right, 
      refer to it as axes[1].'''
axes[0].plot(x,y)

'''3. Title of the 1st subplot'''

axes[0].set_title('x by y cubed')

'''4. X-axis label to 1st subplot'''

axes[0].set_xlabel('Linearly spaced numbers')

'''5. Y-axis label to 1st subplot'''

axes[0].set_ylabel('y-value')

'''6. Plotting the 2nd subplot on the right using y2, x'''

axes[1].plot(x,y1)

'''7. Adding a title to the plot'''

axes[1].set_title('x by y squared')

'''8. X-axis label to 2nd subplot'''

axes[1].set_xlabel('Linearly Spaced numbers')

'''9. Y-axis label to 2nd subplot'''

axes[1].set_ylabel('y-value')

plt.tight_layout()
plt.show()

Activity 3: Multiple plots using subplots

In [162]:
df1 = pd.read_csv("Items_Sold_by_Week.csv")
In [163]:
df1.head()
Out[163]:
Week Items_Sold
0 1 300
1 2 200
2 3 400
3 4 350
4 5 500
In [164]:
df2 = pd.read_csv("Weight_by_Height.csv")
In [165]:
df2.head()
Out[165]:
Height Weight
0 5.0 100
1 5.5 150
2 5.0 110
3 5.5 140
4 6.0 140
In [203]:
'''1. Generating 6 subplots'''

fig, axes = plt.subplots(nrows = 3, ncols = 2,figsize =(10,10))

'''2.Plotting the line plot and Setting the title, xlabel and ylabel'''

axes[0,0].set_title('Line subplot')
axes[0,0].plot(df1['Week'],df1['Items_Sold'])
axes[0,0].set_xlabel('Week')
axes[0,0].set_ylabel('Items_Sold')

'''3.Plotting the bar plot and Setting the title, xlabel and ylabel'''

axes[0,1].set_title('Bar subplot')
axes[0,1].bar(df1['Week'],df1['Items_Sold'])
axes[0,1].set_xlabel('Week')
axes[0,1].set_ylabel('Items_Sold')

'''4.Plotting the horizontal bar plot and Setting the title, xlabel and ylabel'''

axes[1,0].set_title('Horizontal Bar subplot')
axes[1,0].barh(df1['Week'],df1['Items_Sold'])
axes[1,0].set_xlabel('Week')
axes[1,0].set_ylabel('Items_Sold')

'''5.Generating an array of 100 normally distributed numbers to use the 
data for plotting histogram and box and whisker plot'''

X = np.random.normal(loc = 0, scale = 0.1, size = 100) ## Here scale is the standard deviation

'''6. Plotting the histogram from the 100 normally distributed numbers and Setting the title, xlabel and ylabel'''

axes[1,1].set_title('Histogram subplot')
axes[1,1].hist(X,bins = 20)
axes[1,1].set_xlabel('y')
axes[1,1].set_ylabel('Frequency')

'''7. Plotting the boxplot from the 100 normally distributed numbers and Setting the title, xlabel and ylabel'''

axes[2,0].set_title('Box and Whisker subplot')
axes[2,0].boxplot(y)
axes[2,0].set_xlabel('y')
axes[2,0].set_ylabel('Frequency')

'''8. Plotting the scatter plot and setting the title, xlabel and ylabel'''

axes[2,1].set_title('Scatter subplot')
axes[2,1].scatter(df2['Height'],df2['Weight'])
axes[2,1].set_xlabel('Height')
axes[2,1].set_ylabel('Weight')


plt.tight_layout()
plt.show()

'''9. Saving the plots as image'''

fig.savefig("Subplots",bbox_inches='tight')

Reference:

[1] Data Science with Python: Combine Python with Machine Learning Principles to Discover Hidden Patterns in Raw Data :Book by Aaron England, Mohamed Noordeen Alaudeen, and Rohan Chopra.

[2] R Programming for Data Science Book by Roger D. Peng

[3] Statistics for Machine Learning Book by Pratap Dangeti

[4] https://www.kaggle.com/sanikamal/data-visualization-using-matplotlib

In [ ]: