forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot4.R
40 lines (31 loc) · 1.49 KB
/
plot4.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
# Import helper function to download file
source("get_file.R")
file <- get_file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", "./data", "data.zip", unzip = TRUE)
# Extract the file
unzip(file)
data_file_path <- file.path("./household_power_consumption.txt")
# Read the raw data into data
data <- read.table(data_file_path, header = TRUE, sep = ";", colClasses = c(rep("character",2), rep("numeric",7)), na.strings = "?")
# Use dplyr for data manipulation
library(dplyr)
# Use lubridate for date parsing
library(lubridate)
d <- tbl_df(data)
rm("data")
# Filter only the specified date range
# then process the date and time column into one new column called DateTime
selected_data <- filter(d, Date == "2/2/2007" | Date == '1/2/2007') %>%
mutate(DateTime = dmy_hms(paste(Date, Time)))
# Make the 4 plots in a 2x2 canvas and save it as plot4.png
png('./plot4.png')
par(mfrow = c(2,2))
with(selected_data, {
plot(DateTime, Global_active_power, type = "l", xlab = "", ylab = "Global Active Power")
plot(DateTime, Voltage, type = "l", xlab = "datetime", ylab = "Voltage")
plot(DateTime, Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering")
lines(DateTime, Sub_metering_2, col = "red")
lines(DateTime, Sub_metering_3, col = "blue")
legend("topright", lty = 1, col = c("black", "red", "blue"), bty = "n", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(DateTime, Global_reactive_power, type = "l", xlab = "datetime")
})
dev.off()