forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot3.R
58 lines (49 loc) · 2 KB
/
plot3.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
50
51
52
53
54
55
56
57
58
# Get Data
## if data directory doesn´t exist, create
if (!file.exists("data")) {
dir.create("data")
}
## if data doesn´t exist, download and unzip
if (!file.exists("data/EPC.zip")) {
fileURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
zipfile <- "data/EPC.zip"
download.file(fileURL, destfile = zipfile)
unzip(zipfile, exdir = "data")
}
## read data
df <- read.table("data/household_power_consumption.txt", header = TRUE,
sep = ";", na.strings = c("?"), colClasses = c("character",
"character",
"numeric",
"numeric",
"numeric",
"numeric",
"numeric",
"numeric",
"numeric"))
## subset data
subdf <- df[grep("^[1,2]/2/2007", df$Date),]
## create new variable combining date and time
subdf$DateTime <- as.POSIXct(paste(subdf$Date, subdf$Time),
format="%d/%m/%Y %H:%M:%S")
## open png device
png("plot3.png")
## create plot
with(subdf, plot(DateTime,
Sub_metering_1,
type = "n",
xlab = "",
ylab = "Energy sub metering"
)
)
# annotate plot
lines(subdf$DateTime, subdf$Sub_metering_1)
lines(subdf$DateTime, subdf$Sub_metering_2, col = "red")
lines(subdf$DateTime, subdf$Sub_metering_3, col = "blue")
legend("topright",
lty = c(1,1,1),
col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")
)
## close device connection
dev.off()