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
84 lines (64 loc) · 2 KB
/
Copy pathplot3.R
File metadata and controls
84 lines (64 loc) · 2 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
data <- data.frame()
# date range to read from the household power consumption file
begin <- as.Date("2007-02-01")
end <- as.Date("2007-02-02")
# open the data file
data.file <- file("household_power_consumption.txt", "r")
# read the header to start to populate the data frame
column.names <- readLines(data.file, n = 1)
# read the file line by line
while (length(row <- readLines(data.file, n = 1)) > 0) {
row <- strsplit(row, ";")[[1]]
row.date <- as.Date(row[1], format = "%d/%m/%Y")
# accept just those rows between the begin and the end dates
if (row.date >= begin & row.date <= end) {
# add a correctly parsed row
data <- rbind(
data,
data.frame(
row.date,
row[2],
as.numeric(row[3]),
as.numeric(row[4]),
as.numeric(row[5]),
as.numeric(row[6]),
as.numeric(row[7]),
as.numeric(row[8]),
as.numeric(row[9])
)
)
}
}
# assign column names
column.names <- strsplit(column.names, ";")[[1]]
names(data) <- column.names
# close the data file
close(data.file)
# specify the locale to show the weekday names in english
Sys.setlocale("LC_TIME", "English")
# create graphic
png(filename = "plot3.png", width = 480, height = 480)
with (data, {
plot(
as.POSIXlt(paste(Date, Time)),
Sub_metering_1,
xlab = "",
ylab = "Energy sub metering",
type = "l",
col = "black"
)
lines(
as.POSIXlt(paste(Date, Time)),
Sub_metering_2,
col = "red"
)
lines(
as.POSIXlt(paste(Date, Time)),
Sub_metering_3,
col = "blue"
)
})
legend("topright", lty = 1, col = c("black", "red", "blue"),
legend = c("Sub Metering 1", "Sub Metering 2", "Sub Metering 3"))
# save graphic
dev.off()