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
49 lines (45 loc) · 2.26 KB
/
plot3.R
File metadata and controls
49 lines (45 loc) · 2.26 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
#
# Project 1 - Reconstruct Plot 3 of two day household energy usage
#
# USAGE on command line:
# Rscript plot3.R
#
# Note: Path to data and PNG files are hard-coded
# --------------------------------------------------------------------------------------------------
## Load libraries
library(lubridate) # For date manipulation
library(dplyr) # For fixing the data sets
## Read file into a data frame
# Read CSV file; noting that the separator is a semi-colon and header are present
x<-read.csv2("/home/nsubrahm/data/household_power_consumption.txt",header=TRUE,sep=";",stringsAsFactors=FALSE)
# Get the data set into a data frame for manipulation with dplyr
hpc_raw<-tbl_df(x)
## Apply filters
# Filter off the rows whose values are not available. As mentioned in the project description, NA is denoted with ?
hpc_filtered<-filter(hpc_raw,Global_active_power!="?" & Global_reactive_power!="?" & Voltage!="?" & Global_intensity!="?" & Sub_metering_1!="?" & Sub_metering_2!="?" & Sub_metering_3!="?")
# Re-format the string data in data set into a Date object
hpc_mutated<-mutate(hpc_filtered,Date=dmy(Date))
# Then, get only those rows that correspond to 2007-02-01 and 2007-02-02
hpc_days<-filter(hpc_mutated,Date==ymd("2007-02-01") | Date==ymd("2007-02-02"))
# Create time-series with date and time columns
hpc_dateTime<-strptime(paste(hpc_days$Date,hpc_days$Time),format="%Y-%m-%d %H:%M:%S")
# Get energy sub metering 1
hpc_sm1<-as.numeric(hpc_days$Sub_metering_1)
# Get energy sub metering 2
hpc_sm2<-as.numeric(hpc_days$Sub_metering_2)
# Get energy sub metering 3
hpc_sm3<-as.numeric(hpc_days$Sub_metering_3)
# Create a data frame for plotting
hpc<-data.frame(hpc_dateTime,hpc_sm1,hpc_sm2,hpc_sm3)
## Begin plotting to a PNG file
# Open a PNG device
png(filename="/home/nsubrahm/data/plot3.png")
# Create the plot
with(hpc, {
plot(hpc_dateTime,hpc_sm1,type="l",col="black",ylab="Energy metering",xlab="") # Energy sub metering 1
lines(hpc_dateTime,hpc_sm2,col="red") # Energy sub metering 2
lines(hpc_dateTime,hpc_sm3,col="blue") # Energy sub metering 3
legend("topright",col=c("black","red","blue"),legend=c("Sub metering 1","Sub metering 2","Sub metering 3"),lty=c(1,1,1))
})
# Turn off device
dev.off()