Instructions
Requirements and Specifications
Source Code
# **APCO 1P93: Applied Programming (for Data Science)**
### Winter, 2022
### Instructor: Yifeng (Ethan) Li
### Department of Computer Science, Brock University
### Email: <yli2@brocku.ca>
### TA: Tristan Navikevicius: <tn13bm@brocku.ca>
---
## **Assignment 6**
## **<font color=red> Due Date: 10:00pm, Sunday, April 10th, 2022 </font>**
### **<font color=red> Plagiarism = Severe Consequence </font>**
### **<font color=red> Place your work in a zipped folder named _Firstname_Lastname_StudentNumber_ for your submission. </font>**
## **Question 1** (8 points)
The focus of this assignment is to practise drawing plots for climate data using `matplotlib`. A class named `Climate` needs to be defined with data attributes `header`, `time`, and `data`. For your convenience, the structure of this class is given. You will need to do the following tasks.
* Define a method, named `read_data`, of the `Climate` class to read data using function `np.loadtxt` from the given tab-seperated text file. Assign the first row (omiting the first empty field) of the text file to `self.header`, the first column (except the fist row) to `self.time`, and the rest of the data from the text file to `self.data`. **(2 marks)**
* Define a method, named `draw_plots` for the `Climate` class to draw two subplots, respectively, for monthly temperatures and monthly precipitation. For your convenience, you will need to draw both subplots similar to these visualized by the instructor below. After drawing these two plots, you need to save the figure to a pdf file. **(4.5 marks)**
* After defining the class and methods, create an instance, named `c1`, of the `Climate` class. Class methods `read_data` and `draw_plots`. **(1.5 marks)**
import numpy as np
data = np.loadtxt('climate.txt', dtype=str, usecols=(0,1,2,3))
print(data)
import numpy as np
import matplotlib.pyplot as plt
# define your Climate class here
class Climate:
def __init__(self):
self.header = None # will be 1d array of str type, length 4
self.time = None # will be 1d array of str type, length 13
self.data = None # will be 2d array of float type, shape (13,4)
def read_data(self, filename = './climate.txt'):
"""
Read the provided climiate data as string data type.
Assign the header info (first row of the text file, omitting the first field) to self.header.
Assign the month labels and "Year" strings to self.time.
Assign the rows after the first row (omitting the first column) of the text file to self.data.
INPUTS:
filename: string, file name for the given data set.
"""
# (2 marks)
# First, load data without headers
data = np.loadtxt('climate.txt', dtype=str, skiprows=1)
self.time = data[:,0]
self.data = data[:,1:].astype(float)
# Now, load data with headers but ignoring time
data = np.loadtxt('climate.txt', dtype=str, usecols=(0,1,2,3))
self.header = data[0,:]
print('Data from {0} has been successfully loaded.'.format(filename))
print('The data has header:\n{0}'.format(self.header))
print('The data has row names:\n{0}'.format(self.time))
print('There are {0} rows (excluding the header) in the data set.'.format(self.data.shape[0]))
def draw_plots(self):
fig, (ax1, ax2) = plt.subplots(2,1)
fig.set_size_inches((6,8))
fig.set_tight_layout(tight=True)
# draw line subplot (2 marks)
x = range(len(self.time)-1)
# Plot all records except the one for 'year'
ax1.plot(x, self.data[:-1,0], label = 'daily mean', color = 'black', marker = 'o') # daily mean
ax1.plot(x, self.data[:-1,1], linestyle='-.', label = 'average low', color = 'blue', marker = 'v') # avergae low
ax1.plot(x, self.data[:-1,2], linestyle='-.', label = 'average high', color = 'red', marker = '^') # average high
ax1.legend()
ax1.set_xlabel('Month')
ax1.set_ylabel('Temperature (C)')
ax1.set_xticklabels(self.time)
ax1.set_title('Monthly Temperature in St. Catharines')
# draw pie subplot (2 marks)
labels = self.time[:-1]
explode = [0]*12
explode[3] = 0.05 # april
ax2.pie(self.data[:-1,3], explode = explode, labels = labels, autopct='%1.1f%%')
ax2.axis('equal')
ax2.set_title('Monthly Precipitation in St. Catherines', y = -0.1)
# save the drawn figure to a pdf file (0.5 mark)
plt.savefig('figure.pdf', format='pdf')
plt.show()
# creat instance, c1, of class Climate here,
# then call read_data and draw_plots functions.
# (1.5 marks)
c1 = Climate()
c1.read_data()
c1.draw_plots()