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
65 lines (46 loc) · 2.33 KB
/
plot4.R
File metadata and controls
65 lines (46 loc) · 2.33 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
## Function that gets required dataframe from txt file in working directory
## Or returns an error message
getHpcDataframe <- function(){
if("household_power_consumption.txt" %in% list.files()){
print("loading household_power_consumption.txt Dataset.......")
hpc <- read.csv("household_power_consumption.txt", header = TRUE, sep = ";")
print("household_power_consumption.txt Dataset is loaded")
hpc <- hpc[hpc$Date == "1/2/2007" | hpc$Date == "2/2/2007", ]
print("strip by date == 1/2/2007 and 2/2/2007, data is stripped")
print("Adding new column of casted DateTime...")
hpc$DateTime <- strptime(paste(hpc$Date,hpc$Time), "%d/%m/%Y %H:%M:%S")
print("DateTime added")
print("Removing date and time columns...")
hpc$Date <- NULL
hpc$Time <- NULL
hpc <- hpc[,c(8,1,2,3,4,5,6,7)]
print("returning desired dataframe")
return(hpc)
}else{
print("No household_power_consumption.txt file in the working directory")
}
}
## next function uses getHpcDataframe to load the data and construct the graph
makePlot4 <- function(){
hpc <- getHpcDataframe()
if(is.data.frame(hpc)){
hpc$Global_active_power <- as.numeric(hpc$Global_active_power) /500
hpc$Sub_metering_2 <- as.numeric(hpc$Sub_metering_2)
hpc$Sub_metering_2 <- replace(hpc$Sub_metering_2, hpc$Sub_metering_2 == 2, 0)
hpc$Sub_metering_2 <- replace(hpc$Sub_metering_2, hpc$Sub_metering_2 > 3, 4)
png(width=480, height=480, file = "plot4.png")
par(mfrow = c(2,2))
plot(hpc$DateTime,hpc$Global_active_power, type = 'l', ylab = 'Global Active Power (kilowatts)', xlab = '')
plot(hpc$DateTime,hpc$Voltage, type = 'l',col="black", xlab = "datetime", ylab = "Voltage")
plot(hpc$DateTime,hpc$Sub_metering_1, type = 'l',col="black", xlab = "", ylab = "Energy sub metering")
lines(hpc$DateTime,hpc$Sub_metering_2, type = 'l',col="red")
lines(hpc$DateTime,hpc$Sub_metering_3, type = 'l',col="blue")
legend("topright", pch = "_______", col = c("black","red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
plot(hpc$DateTime,hpc$Global_reactive_power, type = 'l',col="black", xlab = "datetime", ylab = "Global_reactive_power")
dev.off()
print("plot4.png is created")
}else{
print("no dataframe to use")
}
}
makePlot4()