forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot2.R
49 lines (36 loc) · 1.85 KB
/
plot2.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# readTable reads the household power consumption table's for dates 2007-02-01 and 2007-02-02
readTable<-function(fileName="household_power_consumption.txt")
{
# Get the class of each column in the file (by reading a snippet of the data and using it as the class to read through data)
tab5rows <- read.table(fileName, header = TRUE, sep = ";", dec = ".", na.strings = "?", nrows = 5)
classes <- sapply(tab5rows, class)
dates<- read.table(fileName , header=TRUE , sep=";" , na.strings="? " , as.is=TRUE , colClasses=c(NA,rep("NULL",ncol(tab5rows)-1)))
newDates<-as.Date(dates$Date,format="%d/%m/%Y")
# Get the index for the start of 2007-02-01 and the number of rows until 2007-02-02 from 2007-02-01
# Assuming the dates are sorted in ascending order
startRow=which.max(newDates >= "2007-02-01")
stopRow=which.max(newDates > "2007-02-02")
nosRowsToRead=stopRow-startRow
# Read data by skipping lines until start of 2007-02-01 and until rows with 2007-02-02
hpc <- read.table(fileName, header = FALSE, sep = ";", dec = ".", na.strings = "?", col.names=colnames(tab5rows), colClasses = classes,skip=startRow-1,nrows=nosRowsToRead)
# Add Data and Time Column to the data set
hpc$DateTime <- strptime(paste(hpc$Date , hpc$Time , sep=" ") , format="%d/%m/%Y %H:%M:%S")
hpc
}
# Function to plot the second figure (plot 2)
plot2<-function()
{
# Read the household_power_consumption.txt data
hpc<-readTable()
# Start the PNG graphic device of 480 x 480 pixels with while background
png(filename="plot2.png" , height=480 , width=480 , units="px", bg = "white")
# Set the number of figures to be drawn
par(mfrow = c(1, 1))
# Plot the figure
plot(x=hpc$DateTime,y=hpc$Global_active_power,type='l',ylab="Globel Active Power (kilowatts)",xlab="")
# Close the device
dev.off()
}
#Plot figure 2
plot2()
message(paste0("figure plot2.png written in directory : ",getwd()))