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()
'''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()
'''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()
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:'
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()
In this exercise we will create bar plot for different items grouped by their sales revenue
''' 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()
''' 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()
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.
''' 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()
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:
'''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()


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.
import numpy as np
x = np.random.normal(loc= 0, scale=0.1, size =100)
plt.hist(x,bins=20)
plt.xlabel('x-value')
plt.ylabel('frequency')
plt.show()
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.
from scipy.stats import shapiro
shap_w, shap_p = shapiro(x)
print("The value of shap_w is {} and shap_p is {}".format(shap_w,shap_p))
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'
plt.title(normal_YN)
plt.hist(x)
plt.show()
x = np.random.normal(loc = 0, scale = 0.1, size= 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.
shap_w, shap_p = shapiro(x)
print("The value of shap_w is {} and the value of shap_p is {}".format(shap_w,shap_p))
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.
from scipy.stats import zscore
XZ_score = zscore(x)
print("The Value of z_scores are {}".format(XZ_score))
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))
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)
plt.title(title)
plt.boxplot(x)
plt.show()
Let's create a scatter plot of weight vs height and programatically create a title which would explain the relationship between these 2 attributes
y = [5, 5.5, 5, 5.5, 6, 6.5, 6, 6.5, 7, 5.5, 5.25, 6, 5.25]
x = [100, 150, 110, 140, 140, 170, 168, 165, 180, 125, 115, 155, 135]
plt.scatter(x,y)
plt.show()
from scipy.stats import pearsonr
correlation_coeff, p_value = pearsonr(x,y)
print("The value of correlation_coeff is {} and the p_value is {}".format(correlation_coeff,p_value))
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)
plt.scatter(x,y)
plt.title(title)
plt.show()
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.
x = np.linspace(0,10,20)
y = x**3
import matplotlib.pyplot as plt
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()
import numpy as np
x = np.linspace(0,10,20)
y = x**3
y1 = x**2
print(x)
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()
'''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()
df1 = pd.read_csv("Items_Sold_by_Week.csv")
df1.head()
df2 = pd.read_csv("Weight_by_Height.csv")
df2.head()
'''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')
[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