forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot4.R
47 lines (42 loc) · 2.09 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
41
42
43
44
45
46
47
###Code to use for subsetting data for plot generation
###Assumes data file is in current working directory
#read some rows to determine class type for each column
first5rows <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", nrows = 5, na.strings = "?")
classes <- sapply(first5rows, class)
#read in all the data using the identified classes
alldata <- read.table("household_power_consumption.txt", header = TRUE, colClasses = classes, sep = ";", nrows = 210000, na.strings = "?")
#convert Date column to Date data class
alldata$Date <- as.Date(alldata$Date, format = '%d/%m/%Y')
min = as.Date("2007-01-31")
max = as.Date("2007-02-03")
#extract the subset of data we want to work with
data <- subset(alldata, Date > min & Date < max)
#remove the larger data set to conserve memory
rm(alldata)
#merge data and time columns to form datetime information
data$datetime <- paste(as.character(data$Date), data$Time, sep = ' ')
#convert datetime from char to date class
data$datetime <- strptime(data$datetime, format='%Y-%m-%d %H:%M:%S')
png(file = "plot4.png", width = 480, height = 480)
#set for a 2x2 panel plot
par(mfrow = c(2, 2))
with(data, {
#replot assignment plot #2
plot(datetime, Global_active_power, pch = '.', ylab ="Global Active Power", xlab = "" )
lines(datetime, Global_active_power)
#replot assignment plot #2, replacing Global_active_power with Voltage and allowing the default x & y labels
plot(datetime, Voltage, pch = '.')
lines(datetime, Voltage)
#replot assignment plot #3
plot(datetime, Sub_metering_1, pch = '.', ylab ="Energy sub metering", xlab = "" )
lines(datetime, Sub_metering_1)
lines(datetime, Sub_metering_2, col = 'red')
lines(datetime, Sub_metering_3, col = "blue")
legend( x="topright",
legend=c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"),
col=c("black", "red", "blue"), lty=c(1,1,1), bty = "n")
#replot assignment plot #2, replacing Global_active_power with Global_reactive_power and allowing the default x & y labels
plot(datetime, Global_reactive_power, pch = '.' )
lines(datetime, Global_reactive_power)
})
dev.off()