forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot4.R
More file actions
53 lines (49 loc) · 2.18 KB
/
plot4.R
File metadata and controls
53 lines (49 loc) · 2.18 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
## This file is the solution for Course Proj 1
## Read the data content at dates 1 and 2/2/2007
# Use regular expression to search for the dates
# at the beginning of each line (^)
# and output the text (value = TRUE)
f <- readLines("household_power_consumption.txt")
dayMatch <- grep("^[1,2]/2/2007", f, value = TRUE)
# Combine the text with col names, set sep and na.string
# also set colClasses and nrows for efficient read
data <- read.table(text = c(f[1],dayMatch),
header = TRUE,
sep = ";",
na.strings = "?",
colClasses = c(rep("character", 2), rep("numeric", 7)),
nrows = length(dayMatch)+1)
data$Date <- as.Date(data$Date, "%d/%m/%Y")
# Plot 4
png(filename = "plot4.png",
width = 480, height = 480, units = "px")
yrange <- with(data, range(c(Sub_metering_1,Sub_metering_2,Sub_metering_3)))
par(mfrow = c(2,2))
# Graph 1
with(data, plot(Global_active_power,
xaxt = "n", type = "l",
xlab = "", ylab = "Global Active Power"))
axis(side = 1, at = c(1,2880/2,2880),
labels = c("Thu", "Fri", "Sat"))
# Graph 2
with(data, plot(Voltage, xaxt = "n", type = "l", xlab = "datetime", ylab = "Voltage"))
axis(side = 1, at = c(1,2880/2,2880),
labels = c("Thu", "Fri", "Sat"))
# Graph 3
yrange <- with(data, range(c(Sub_metering_1,Sub_metering_2,Sub_metering_3)))
with(data, plot(Sub_metering_1, xaxt = "n", ylim = yrange, type = "l", xlab = "", ylab = ""))
par(new=T)
with(data, plot(Sub_metering_2, xaxt = "n", ylim = yrange, type = "l", xlab = "", ylab = "", col = "red"))
par(new=T)
with(data, plot(Sub_metering_3, xaxt = "n", ylim = yrange, type = "l", xlab = "", ylab = "", col = "blue"))
par(new=F)
axis(side = 1, at = c(1,2880/2,2880),
labels = c("Thu", "Fri", "Sat"))
title(ylab = "Energy sub metering")
legend("topright", lty = c(1,1,1), lwd = c(2.5, 2.5, 2.5), col = c("black", "blue", "red"), bty = "n",
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
# Graph 4
with(data, plot(Global_reactive_power, xaxt = "n", type = "l", xlab = "datetime"))
axis(side = 1, at = c(1,2880/2,2880),
labels = c("Thu", "Fri", "Sat"))
dev.off()