-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Data Science with Python
By :

Solution:
x = ['January','February','March','April','May','June']
y = [1000, 1200, 1400, 1600, 1800, 2000]
plt.plot(x, y, '*:b')
plt.xlabel('Month')
plt.ylabel('Items Sold')
plt.title('Items Sold has been Increasing Linearly')
Check out the following screenshot for the resultant output:
Solution:
x = ['Boston Celtics','Los Angeles Lakers', 'Chicago Bulls', 'Golden State Warriors', 'San Antonio Spurs']
y = [17, 16, 6, 6, 5]
import pandas as pd
df = pd.DataFrame({'Team': x,
'Titles': y})
df_sorted = df.sort_values(by=('Titles'), ascending=False)
If we sort with ascending=True, the plot will have larger values to the right. Since we want the larger values on the left, we will be using ascending=False.
team_with_most_titles = df_sorted['Team'][0]
most_titles = df_sorted['Titles'][0]
title = 'The {} have the most titles with {}'.format(team_with_most_titles, most_titles)
import matplotlib.pyplot as plt
plt.bar(df_sorted['Team'], df_sorted['Titles'], color='red')
plt.xlabel('Team')
plt.ylabel('Number of Championships')
plt.xticks(rotation=45)
plt.title(title)
plt.savefig('Titles_by_Team)
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.
The following figure displays the bar plot with the cropped x tick labels.
plt.savefig('Titles_by_Team', bbox_inches='tight')
Check out the following output for the final result:
Solution:
import pandas as pd
Items_by_Week = pd.read_csv('Items_Sold_by_Week.csv')
Weight_by_Height = pd.read_csv('Weight_by_Height.csv')
y = np.random.normal(loc=0, scale=0.1, size=100)
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=3, ncols=2)
plt.tight_layout()
axes[0,0].set_title('Line')
axes[0,1].set_title('Bar')
axes[1,0].set_title('Horizontal Bar')
axes[1,1].set_title('Histogram')
axes[2,0].set_title('Scatter')
axes[2,1].set_title('Box-and-Whisker')
axes[0,0].plot(Items_by_Week['Week'], Items_by_Week['Items_Sold'])
axes[0,1].bar(Items_by_Week['Week'], Items_by_Week['Items_Sold'])
axes[1,0].barh(Items_by_Week['Week'], Items_by_Week['Items_Sold'])
See the resultant output in the following figure:
axes[1,1].hist(y, bins=20)axes[2,1].boxplot(y)
The resultant output is displayed here:
axes[2,0].scatter(Weight_by_Height['Height'], Weight_by_Height['Weight'])
See the figure here for the resultant output:
See the figure here for the resultant output:
fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(8,8))
fig.savefig('Six_Subplots')
The following figure displays the 'Six_Subplots.png' file:
Change the font size
Change margin width
Change background colour