forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot3.R
More file actions
49 lines (43 loc) · 2.34 KB
/
plot3.R
File metadata and controls
49 lines (43 loc) · 2.34 KB
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
## The overall goal is simply to examine how household energy usage varies over
## a 2-day period in February, 2007.
## This function will be using the "Individual household electric power
## consumption Data Set" from the UC Irvine Machine Learning Repository.
## This function constructs the plot of energy sub-metering No. 1, No. 2, and
## No. 3 over time using the base plotting system.
plot3 <- function() {
fileurl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
zipfile <- "exdata-data-household_power_consumption.zip"
filename <- "household_power_consumption.txt"
## Check the existence of the dataset
## If the dataset is not exist but is downloaded in a zipfile,
## unzip the dataset
## If the dataset is not exist and the zipfile is not downloaded,
## download the dataset and unzip the dataset from the zipfile
if(!file.exists(filename)) {
if(!file.exists(zipfile)) {
download.file(fileurl, zipfile, method = "curl")
}
unzip(zipfile)
unlink(zipfile)
}
## Load data from the dates 2007-02-01 and 2007-02-02
## and construct a list of the class "POSIXlt"
start <- grep("1/2/2007", readLines(filename))[1]
end <- grep("3/2/2007", readLines(filename))[1]
data <- read.table(filename, sep = ";", na.strings = "?",
skip = start - 1, nrows = end - start)
data <- data[complete.cases(data), ]
date_time <- paste(data[, 1], data[, 2])
completeTime <- strptime(date_time, format = "%d/%m/%Y %H:%M:%S")
## Construct the plot of Energy sub metering over time
## and save it to a PNG file
## with a width of 480 pixels and a height of 480 pixels (default)
png("plot3.png", bg = "transparent")
plot(completeTime, as.numeric(data[, 7]), type = "l",
ylab = "Energy sub metering", xlab = "")
lines(completeTime, as.numeric(data[, 8]), col = "red")
lines(completeTime, as.numeric(data[, 9]), col = "blue")
legend("topright", lwd = 1, col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
}